Python内置函数(11)——classmethod

英文文档:

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'>
类实例对象调用类方法
  1. 类被继承后,子类也可以调用父类的类方法,但是第一个参数传入的是子类的类对象
>>> class D(C): 
       pass
>>> D.f("子类的类对象调用父类的类方法")
<class '__main__.D'>
子类的类对象调用父类的类方法
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 2,082评论 0 9
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,680评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 34,819评论 18 399
  • Jni数据类型 Jni方法 来自 http://blog.chinaunix.net/uid-22028680-i...
    FlyDragonInSky阅读 1,008评论 0 0
  • crontab -e 来生成计划任务,实际上是在/var/spool/cron下对应账号添加一条记录, 如当前登录...
    ghbsunny阅读 1,258评论 0 0

友情链接更多精彩内容