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)記方法為類方法的裝飾器
說明:
1. classmethod 是一個(gè)裝飾器函數(shù),用來標(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. 詳細(xì)總結(jié)Java for循環(huán)的那些坑2. python文件處理--文件讀寫詳解3. Java進(jìn)行Appium自動(dòng)化測(cè)試的實(shí)現(xiàn)4. Python通過format函數(shù)格式化顯示值5. 新手學(xué)python應(yīng)該下哪個(gè)版本6. jsp文件下載功能實(shí)現(xiàn)代碼7. uni-app結(jié)合PHP實(shí)現(xiàn)單用戶登陸demo及解析8. 如何利用Python matplotlib繪制雷達(dá)圖9. ajax實(shí)現(xiàn)頁面的局部加載10. 詳解CSS偽元素的妙用單標(biāo)簽之美

網(wǎng)公網(wǎng)安備