Python里的instance method, classmethod与staticmethod

来源:互联网 发布:软件开发工资待遇 编辑:程序博客网 时间:2024/06/18 01:03

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

用一个表格总结如下:

方法类型 修饰 调用者 默认首参 实例方法 无 instance self 类方法 @classmethod cls, instance cls 静态方法 @staticmethod cls, 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.

原创粉丝点击