英文文档:
classmethod(function)
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> >>> class C: @classmethod def f(cls,arg1): print(cls) print(arg1) >>> C.f('类对象调用类方法') <class '__main__.C'> 类对象调用类方法 >>> c = C() >>> c.f('类实例对象调用类方法') <class '__main__.C'> 类实例对象调用类方法
4. 类被继承后,子类也可以调用父类的类方法,但是第一个参数传入的是子类的类对象
>>> class D(C): pass >>> D.f("子类的类对象调用父类的类方法") <class '__main__.D'> 子类的类对象调用父类的类方法
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
Python classmethod装饰器原理及用法解析
扫一扫手机访问
