17 实例方法、静态方法、类方法

举例

class Person(object):
    # 实例方法
    def eat(self):
        print(self)
        print("this is eat")

    # 静态方法
    @staticmethod
    def say():
        print("Saying....")

    # 类方法
    @classmethod
    def play(cls):
        print(cls)
        print("this is play")


print("1.")
york = Person()

print("2.")  # 调用实例方法
Person.eat(york)
york.eat()

print("3.")  # 调用静态方法
Person.say()
york.say()

print("4.")  # 调用类方法
Person.play()
york.play()

>>>

1.
2.
<__main__.Person object at 0x000001CCF8DAC2E8>
this is eat
<__main__.Person object at 0x000001CCF8DAC2E8>
this is eat
3.
Saying....
Saying....
4.
<class '__main__.Person'>
this is play
<class '__main__.Person'>
this is play

分析

  • 实例方法

    • 第一个参数必须是实例对象,其“预定俗成”的参数名为 self
    • 可以被类对象和实例对象调用
    • 被类对象调用时需要传入具体对象
  • 静态方法

    • 使用装饰器 @staticmethod
    • 没有参数 selfcls,但可以有其它参数
    • 方法体中不能使用类或实例的任何属性和方法
    • 可以被类对象和实例对象调用
  • 类方法

    • 使用装饰器 @classmethod
    • 第一个参数必须是当前类对象,其“预定俗成”的参数名为 cls
    • 可以被类对象和实例对象调用
  • 其它结论

    • 实例方法针对的是实例
    • 类方法针对的是类
    • 实例方法和类方法都可以继承和重新定义
    • 静态方法不能继承,可以当作“全局函数”
原文地址:https://www.cnblogs.com/yorkyu/p/10713014.html