Python 内建函数 - classmethod(function)

时间:2021-12-12 18:38:09

Manual

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.

For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

直译

function返回类方法。
一个类方法将类作为第一个隐式参数接收,就好比实例方法接收实例一样。声明一个类方法使用以下语句:

class C:
@classmethod
def f(cls, arg1, arg2, ...): ...

@classmethod是函数修饰器 — 详情见函数定义。其既可在类上调用(如C.f()),也可在实例上调用(如C().f())。除了类外,将忽略其实例。如果一个类方法被衍生类调用,衍生类对象将作为第一个隐式参数传入。类方法不同于C++或Java的静态方法,如果需要,参见staticmethod()
如果需要获得更多关于类方法的信息,可参考标准类型分层

实例

绑定实例

>>> class CSDN:
def log(self):
print('Hello world!')
>>> CSDN.log()
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
CSDN.log()
TypeError: log() missing 1 required positional argument: 'self'
>>> c = CSDN()
>>> c.log()
Hello world!
>>> classmethod(c.log())
Hello world!
<classmethod object at 0x03912030>

修饰器绑定类方法

>>> class CSDN:
@classmethod
def log(self):
print('Hello world!')
>>> CSDN.log()
Hello world!
>>> c = CSDN()
>>> c.log()
Hello world!
>>> class foo(CSDN):
def __init__(self):
print('Loading...')
>>> foo.log()
Hello world!
>>> foo().log()
Loading...
Hello world!

拓展阅读

修饰器
函数定义
staticmethod()
标准类型分层