中文說明:
classmethod是用來指定一個類別的方法為類別方法,沒有此參數指定的類別的方法為實例方法,使用方法如下:
class C: @classmethod def f(cls, arg1, arg2, ...): ...
類別方法既可以直接類別呼叫(C.f()),也可以進行實例呼叫(C().f())。
版本:python2.2新增,在python2.4中增加新功能。 python3中仍可使用。
英文說明:
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.
Ittails.## 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。 on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.New in version 2.2.
Changed in version 2.4: Function decorator
#Changed in version 2.4: Function decorator-ntunction decorators ntunction csyntnt .程式碼實例:
>>> class C: ... @classmethod ... def f(self): ... print "This is a class method" ... >>> C.f() This is a class method >>> c = C() >>> c.f() This is a class method >>> class D: ... def f(self): ... print " This is not a class method " ... >>> D.f() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unbound method f() must be called with D instance as first argument (got nothing instead) >>> d = D() >>> d.f() This is not a class method
以上是python函數之classmethod()的詳細內容。更多資訊請關注PHP中文網其他相關文章!