Python里的instance method, classmethod与staticmethod

在Python里, 在class里定义的方法可以大致分为三类: 实例方法, 类方法与静态方法.

用一个表格总结如下:

方法类型修饰调用者默认首参
实例方法instanceself
类方法@classmethodcls, instancecls
静态方法@staticmethodcls, instance

示例:

class Foo():
    # 无修饰
    def instance_method(self): #传入的第一个参数是self, 即instance本身
        print('the first argument of instance_method:', self)

    @classmethod
    def class_method(cls): # 传入的第一个参数是class
        print('the first argument of class_method:', cls)

    @staticmethod
    def static_method(): # 没有默认的首位参数, 只有自定义参数
        print('the first argument of static_method:')

foo = Foo()
foo.instance_method()
Foo.class_method()
foo.class_method()
Foo.static_method()
foo.static_method()
try:
    Foo.instance_method()
except:
    print('instance method can not be accessed through class.')

输出:

the first argument of instance_method: <__main__.Foo object at 0x7fd135ec3b38>
the first argument of class_method: <class '__main__.Foo'>
the first argument of class_method: <class '__main__.Foo'>
the first argument of static_method:
the first argument of static_method:
instance method can not be accessed through class

需要注意:
1. @classmethod@staticmethod是Python的built-in methods.
2. 特殊方法__new__虽然不用@classmethod修饰, 但它也是class method.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值