python函数

classmethod(function)

中文说明:

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.

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

Posted in 未分类

发表评论