日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

内置装饰器一:@classmethod、@staticmathod

發(fā)布時間:2025/5/22 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 内置装饰器一:@classmethod、@staticmathod 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

使用 @classmethod 和 @staticmathod 后,類的方法的調(diào)用

  • 一般來說,要使用某個類的方法,需要先實例化一個對象再調(diào)用方法。
  • 而使用@staticmethod或@classmethod,就可以不需要實例化,直接類名.方法名()來調(diào)用。
    這有利于組織代碼,把某些應(yīng)該屬于某個類的函數(shù)給放到那個類里去,同時有利于命名空間的整潔。

@staticmethod 和 @classmethod 都可以直接類名.方法名()來調(diào)用,他們的區(qū)別

  • @staticmethod 不需要表示自身對象的 self 和自身類的 cls 參數(shù),就跟使用函數(shù)一樣。
  • @classmethod 也不需要 self 參數(shù),但第一個參數(shù)需要是表示自身類的 cls 參數(shù)。
  • 如果在 @staticmethod 中要調(diào)用到這個類的一些屬性方法,只能直接類名.屬性名或類名.方法名。
  • 而 @classmethod 因為持有 cls 參數(shù),可以來調(diào)用類的屬性,類的方法,實例化對象等,避免硬編碼。

總結(jié):
簡單使用的時候使用@staticmethod, 需要調(diào)用類的其他屬性時使用@classmethod

示例

# -*- coding: utf-8 -*-class Washer:company = "Li"def __init__(self,water=10,scour=2):self._water = waterself.scour = scourself.year = 2010@staticmethoddef spins_ml(spins):# print("company:",Washer.company)# print('year:',self.year)return spins * 0.4@classmethoddef get_washer(cls,water,scour):print("company:",Washer.company)print('year:',self.year)return cls(water,cls.spins_ml(scour))@propertydef water(self):return self._water@water.setterdef water(self,water):if 0 < water <=500:self._water = waterelse:print("set Failure!")@propertydef total_year(self):return 2015 - self.yeardef set_water(self,water):self.water = waterdef set_scour(self,scour):self.scour = scourdef add_water(self):print('Add water:',self.water)def add_scour(self):print('Add scour:',self.scour)def start_wash(self):self.add_water()self.add_scour()print('Start wash...')

參考資料:http://blog.willdx.me/web/面向?qū)ο筮M階.html

轉(zhuǎn)載于:https://www.cnblogs.com/ronky/p/9884155.html

總結(jié)

以上是生活随笔為你收集整理的内置装饰器一:@classmethod、@staticmathod的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。