[Python3 填坑] 017 实例方法、静态方法、类方法的区别


1. print( 坑的信息 )

  • 挖坑时间:2019/04/07
  • 明细
坑的编码 内容
Py024-1 实例方法、静态方法、类方法的区别



2. 开始填坑

2.1 先上例子

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


2.2 分析

  • 实例方法
    • 第一个参数必须是实例对象,其“预定俗成”的参数名为 self
    • 可以被类对象和实例对象都调用
    • 被类对象调用时需要传入具体对象
  • 静态方法
    • 使用装饰器 @staticmethod
    • 没有参数 selfcls,但可以有其它参数
    • 方法体中不能使用类或实例的任何属性和方法
    • 可以被类对象和实例对象都调用
  • 类方法
    • 使用装饰器 @classmethod
    • 第一个参数必须是当前类对象,其“预定俗成”的参数名为 cls
    • 可以被类对象和实例对象都调用
  • 其它结论
    • 实例方法针对的是实例
    • 类方法针对的是类
    • 实例方法和类方法都可以继承和重新定义
    • 静态方法不能继承,可以当作“全局函数”

猜你喜欢

转载自www.cnblogs.com/yorkyu/p/10713014.html