python中的class_static的@classmethod的巧妙用法
python中的class_static的@classmethod的使用 classmethod的使用,主要針對(duì)的是類而不是對(duì)象,在定義類的時(shí)候往往會(huì)定義一些靜態(tài)的私有屬性,但是在使用類的時(shí)候可能會(huì)對(duì)類的私有屬性進(jìn)行修改,但是在沒有使用class method之前對(duì)于類的屬性的修改只能通過對(duì)象來進(jìn)行修改,這是就會(huì)出現(xiàn)一個(gè)問題當(dāng)有很多對(duì)象都使用這個(gè)屬性的時(shí)候我們要一個(gè)一個(gè)去修改對(duì)象嗎?答案是不會(huì)出現(xiàn)這么無腦的程序,這就產(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(’蘋果’,5)print(apple.price)Goods.change(0.5) #這里就不是使用apple.change()進(jìn)行修改了print(apple.price)
上面只是簡單的列舉了class method的一種使用場景,后續(xù)如果有新的會(huì)持續(xù)更新本篇文章 2.既然@staticmethod和@classmethod都可以直接類名.方法名()來調(diào)用,那他們有什么區(qū)別呢
從它們的使用上來看,@staticmethod不需要表示自身對(duì)象的self和自身類的cls參數(shù),就跟使用函數(shù)一樣。@classmethod也不需要self參數(shù),但第一個(gè)參數(shù)需要是表示自身類的cls參數(shù)。
如果在@staticmethod中要調(diào)用到這個(gè)類的一些屬性方法,只能直接類名.屬性名或類名.方法名。而@classmethod因?yàn)槌钟衏ls參數(shù),可以來調(diào)用類的屬性,類的方法,實(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用法
需求:添加類對(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. python公司內(nèi)項(xiàng)目對(duì)接釘釘審批流程的實(shí)現(xiàn)2. Python中Anaconda3 安裝gdal庫的方法3. Python本地及虛擬解釋器配置過程解析4. Python 簡介5. Python importlib模塊重載使用方法詳解6. Python 利用flask搭建一個(gè)共享服務(wù)器的步驟7. python用zip壓縮與解壓縮8. Python操作Excel工作簿的示例代碼(*.xlsx)9. Python自動(dòng)化之定位方法大殺器xpath10. Notepad++如何配置python?配置python操作流程詳解
