python中的class_static的@classmethod的巧妙用法
python中的class_static的@classmethod的使用 classmethod的使用,主要針對的是類而不是對象,在定義類的時候往往會定義一些靜態的私有屬性,但是在使用類的時候可能會對類的私有屬性進行修改,但是在沒有使用class method之前對于類的屬性的修改只能通過對象來進行修改,這是就會出現一個問題當有很多對象都使用這個屬性的時候我們要一個一個去修改對象嗎?答案是不會出現這么無腦的程序,這就產生classmethod的妙用。請看下面的代碼:
class Goods: __discount = 0.8 def __init__(self,name,money):self.__name = nameself.__money = money @property def price(self):return self.__money*Goods.__discount @classmethod def change(cls,new_discount):#注意這里不在是self了,而是cls進行替換cls.__discount = new_discountapple = Goods(’蘋果’,5)print(apple.price)Goods.change(0.5) #這里就不是使用apple.change()進行修改了print(apple.price)
上面只是簡單的列舉了class method的一種使用場景,后續如果有新的會持續更新本篇文章 2.既然@staticmethod和@classmethod都可以直接類名.方法名()來調用,那他們有什么區別呢
從它們的使用上來看,@staticmethod不需要表示自身對象的self和自身類的cls參數,就跟使用函數一樣。@classmethod也不需要self參數,但第一個參數需要是表示自身類的cls參數。
如果在@staticmethod中要調用到這個類的一些屬性方法,只能直接類名.屬性名或類名.方法名。而@classmethod因為持有cls參數,可以來調用類的屬性,類的方法,實例化對象等,避免硬編碼。下面上代碼。
class A(object): bar = 1 def foo(self): print ’foo’ @staticmethod def static_foo(): print ’static_foo’ print A.bar @classmethod def class_foo(cls): print ’class_foo’ print cls.bar cls().foo() ###執行 A.static_foo() A.class_foo()
知識點擴展:python classmethod用法
需求:添加類對象屬性,在新建具體對象時使用該變量
class A(): def __init__(self,name):self.name = nameself.config = {’batch_size’:A.bs} @classmethod def set_bs(cls,bs):cls.bs = bs def print_config(self):print (self.config) A.set_bs(4)a = A(’test’)a.print_config()
以上就是python中的class_static的@classmethod的使用的詳細內容,更多關于python classmethod使用的資料請關注好吧啦網其它相關文章!
相關文章: