坑的编码 | 内容 |
---|---|
Py024-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
self
@staticmethod
self
或 cls
,但可以有其它参数@classmethod
cls
[Python3 填坑] 017 实例方法、静态方法、类方法的区别
原文:https://www.cnblogs.com/yorkyu/p/10713014.html