python函数每日一讲 - classmethod()

kkkkk 2018年12月17日 23:08 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 "<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


文章评论(0)
  • avatar kkkkkk 2018年12月21日 11:31
    python学院最帅的是谁啊?
    kkkkk
    2018年12月21日 11:16
    本文紧扣材料,提出中心论点,进而由现象到本质,扣住概念本身加以阐释,并推论到其他。符合题意,内容充实。论述过程有条不紊地深入分析,摆事实讲道理,论述简洁。文章分析深刻,很好地体现了辩证思维,材料较丰富。
    回复
  • avatar kkkkkk 2018年12月21日 11:31
    潭州python学院老师真棒!
    kkkkklxinde
    2018年12月21日 11:17
    语言表达准确、流畅,表现力强。
    回复
  • avatar kkkkklxinde 2018年12月21日 11:17
    语言表达准确、流畅,表现力强。
    回复
  • avatar kkkkk 2018年12月21日 11:16
    本文紧扣材料,提出中心论点,进而由现象到本质,扣住概念本身加以阐释,并推论到其他。符合题意,内容充实。论述过程有条不紊地深入分析,摆事实讲道理,论述简洁。文章分析深刻,很好地体现了辩证思维,材料较丰富。
    回复