python解析器原理_Python 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('类对象调用类方法')

类对象调用类方法

>>> c = c()

>>> c.f('类实例对象调用类方法')

类实例对象调用类方法

4. 类被继承后,子类也可以调用父类的类方法,但是第一个参数传入的是子类的类对象

>>> class d(c):

pass

>>> d.f("子类的类对象调用父类的类方法")

子类的类对象调用父类的类方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值