Python classmethod裝飾器原理及用法解析
英文文檔:
classmethod(function)
Return a class method for function.
A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
class C:@classmethoddef f(cls, arg1, arg2, ...): ...The @classmethod form is a function decorator ? see the description of function definitions in Function definitions for details.
It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.
標(biāo)記方法為類方法的裝飾器
說(shuō)明:
1. classmethod 是一個(gè)裝飾器函數(shù),用來(lái)標(biāo)示一個(gè)方法為類方法
2. 類方法的第一個(gè)參數(shù)是類對(duì)象參數(shù),在方法被調(diào)用的時(shí)候自動(dòng)將類對(duì)象傳入,參數(shù)名稱約定為cls
3. 如果一個(gè)方法被標(biāo)示為類方法,則該方法可被類對(duì)象調(diào)用(如 C.f()),也可以被類的實(shí)例對(duì)象調(diào)用(如 C().f())
>>> class C: @classmethod def f(cls,arg1): print(cls) print(arg1) >>> C.f(’類對(duì)象調(diào)用類方法’)<class ’__main__.C’>類對(duì)象調(diào)用類方法>>> c = C()>>> c.f(’類實(shí)例對(duì)象調(diào)用類方法’)<class ’__main__.C’>類實(shí)例對(duì)象調(diào)用類方法
4. 類被繼承后,子類也可以調(diào)用父類的類方法,但是第一個(gè)參數(shù)傳入的是子類的類對(duì)象
>>> class D(C): pass>>> D.f('子類的類對(duì)象調(diào)用父類的類方法')<class ’__main__.D’>子類的類對(duì)象調(diào)用父類的類方法
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法2. SpringBoot集成SSM、Dubbo、Redis、JSP的案例小結(jié)及思路講解3. python爬蟲利用代理池更換IP的方法步驟4. JavaScript forEach中return失效問題解決方案5. JS算法題解旋轉(zhuǎn)數(shù)組方法示例6. PHP設(shè)計(jì)模式之迭代器模式Iterator實(shí)例分析【對(duì)象行為型】7. VMware如何進(jìn)入BIOS方法8. python中pandas.read_csv()函數(shù)的深入講解9. Python語(yǔ)言規(guī)范之Pylint的詳細(xì)用法10. springboot用controller跳轉(zhuǎn)html頁(yè)面的實(shí)現(xiàn)
