脚本专栏 
首页 > 脚本专栏 > 浏览文章

Python classmethod装饰器原理及用法解析

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

英文文档:

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 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.

  标记方法为类方法的装饰器

说明:

  1. classmethod 是一个装饰器函数,用来标示一个方法为类方法

  2. 类方法的第一个参数是类对象参数,在方法被调用的时候自动将类对象传入,参数名称约定为cls

  3. 如果一个方法被标示为类方法,则该方法可被类对象调用(如 C.f()),也可以被类的实例对象调用(如 C().f())

> 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基于locals返回作用域字典
下一篇:Python基于staticmethod装饰器标示静态方法
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网