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 优快云:
def log(self):
print('Hello world!')
>>> 优快云.log()
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
优快云.log()
TypeError: log() missing 1 required positional argument: 'self'
>>> c = 优快云()
>>> c.log()
Hello world!
>>> classmethod(c.log())
Hello world!
<classmethod object at 0x03912030>
修饰器绑定类方法
>>> class 优快云:
@classmethod
def log(self):
print('Hello world!')
>>> 优快云.log()
Hello world!
>>> c = 优快云()
>>> c.log()
Hello world!
>>> class foo(优快云):
def __init__(self):
print('Loading...')
>>> foo.log()
Hello world!
>>> foo().log()
Loading...
Hello world!
Python 中的 classmethod 和函数修饰器
Python 的 classmethod 内建函数用于创建类方法,它接收类作为第一个参数而不是实例。类方法可以通过类或实例调用,并在派生类调用时接收派生类对象。区别于 C++ 或 Java 的静态方法,Python 还提供了 staticmethod 用于类似功能。类方法的详细信息可以在 Python 的标准类型层次结构文档中找到。
3116

被折叠的 条评论
为什么被折叠?



