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. Android table布局開發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器2. 理解PHP5中static和const關(guān)鍵字3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. IntelliJ IDEA安裝插件的方法步驟6. phpstorm恢復(fù)默認(rèn)設(shè)置的方法步驟7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫(kù)使用方法及異常處理方案9. Vuex localStorage的具體使用10. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟

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