classmethod(function)
中文说明:
classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,使用方法如下:
class C: @classmethod def f(cls, arg1, arg2, ...): ...
登录后复制登录后复制
立即学习“Python免费学习笔记(深入)”;
类方法既可以直接类调用(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, ...): ...
登录后复制登录后复制
立即学习“Python免费学习笔记(深入)”;
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.
New in version 2.2.
Changed in version 2.4: Function decorator syntax added.
代码实例:
>>> 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 "", line 1, in 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
登录后复制
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2285170.html