英文文檔:
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:
@classmethod
def 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.
說明:
classmethod 是一個裝飾器函數(shù)葱跋,用來標(biāo)示一個方法為類方法
類方法的第一個參數(shù)是類對象參數(shù),在方法被調(diào)用的時候自動將類對象傳入,參數(shù)名稱約定為cls
如果一個方法被標(biāo)示為類方法娱俺,則該方法可被類對象調(diào)用(如 C.f())稍味,也可以被類的實例對象調(diào)用(如 C().f())
>>> class C:
@classmethod
def f(cls,arg1):
print(cls)
print(arg1)
>>> C.f('類對象調(diào)用類方法')
<class '__main__.C'>
類對象調(diào)用類方法
>>> c = C()
>>> c.f('類實例對象調(diào)用類方法')
<class '__main__.C'>
類實例對象調(diào)用類方法
- 類被繼承后,子類也可以調(diào)用父類的類方法荠卷,但是第一個參數(shù)傳入的是子類的類對象
>>> class D(C):
pass
>>> D.f("子類的類對象調(diào)用父類的類方法")
<class '__main__.D'>
子類的類對象調(diào)用父類的類方法