python中的class_static的@classmethod的巧妙用法
python中的class_static的@classmethod的使用 classmethod的使用,主要針對(duì)的是類(lèi)而不是對(duì)象,在定義類(lèi)的時(shí)候往往會(huì)定義一些靜態(tài)的私有屬性,但是在使用類(lèi)的時(shí)候可能會(huì)對(duì)類(lèi)的私有屬性進(jìn)行修改,但是在沒(méi)有使用class method之前對(duì)于類(lèi)的屬性的修改只能通過(guò)對(duì)象來(lái)進(jìn)行修改,這是就會(huì)出現(xiàn)一個(gè)問(wèn)題當(dāng)有很多對(duì)象都使用這個(gè)屬性的時(shí)候我們要一個(gè)一個(gè)去修改對(duì)象嗎?答案是不會(huì)出現(xiàn)這么無(wú)腦的程序,這就產(chǎn)生classmethod的妙用。請(qǐng)看下面的代碼:
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進(jìn)行替換cls.__discount = new_discountapple = Goods(’蘋(píng)果’,5)print(apple.price)Goods.change(0.5) #這里就不是使用apple.change()進(jìn)行修改了print(apple.price)
上面只是簡(jiǎn)單的列舉了class method的一種使用場(chǎng)景,后續(xù)如果有新的會(huì)持續(xù)更新本篇文章 2.既然@staticmethod和@classmethod都可以直接類(lèi)名.方法名()來(lái)調(diào)用,那他們有什么區(qū)別呢
從它們的使用上來(lái)看,@staticmethod不需要表示自身對(duì)象的self和自身類(lèi)的cls參數(shù),就跟使用函數(shù)一樣。@classmethod也不需要self參數(shù),但第一個(gè)參數(shù)需要是表示自身類(lèi)的cls參數(shù)。
如果在@staticmethod中要調(diào)用到這個(gè)類(lèi)的一些屬性方法,只能直接類(lèi)名.屬性名或類(lèi)名.方法名。而@classmethod因?yàn)槌钟衏ls參數(shù),可以來(lái)調(diào)用類(lèi)的屬性,類(lèi)的方法,實(shí)例化對(duì)象等,避免硬編碼。下面上代碼。
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() ###執(zhí)行 A.static_foo() A.class_foo()
知識(shí)點(diǎn)擴(kuò)展:python classmethod用法
需求:添加類(lèi)對(duì)象屬性,在新建具體對(duì)象時(shí)使用該變量
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的使用的詳細(xì)內(nèi)容,更多關(guān)于python classmethod使用的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis2. Python 忽略文件名編碼的方法3. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作4. 解決vue頁(yè)面刷新,數(shù)據(jù)丟失的問(wèn)題5. Java Media Framework 基礎(chǔ)教程6. android studio實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器(無(wú)bug)7. 在Mac中配置Python虛擬環(huán)境過(guò)程解析8. 利用單元測(cè)試對(duì)PHP代碼進(jìn)行檢查9. python excel和yaml文件的讀取封裝10. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML
