class Apple():
@classmethod
def color(cls):
print("color")
def size(cls):
print("color")
@staticmethod
def shape():
print("color")
a = Apple()
print(a.color)
print(a.size)
print(a.shape)
"""
>
>
在class内定义的类方法(color),它第一个参数必须是cls,并与class本身是绑定关系,它也属于方法,但不属于实例方法,可以被实例对象调用。
在class内定义的普通方法(size),因为它是要面向实例化对象的一个实例方法。
在class内定义的静态方法(shape),它与任何对象都没有联系,等同于是在class外定义的function,它属于函数。
"""
那为什么要有类方法呢?
类方法主要区分与实例方法,实例方法只修改具体实例的属性,类方法可以修改整个类下所有实例的属性。
本博客源码Github地址:
请随手给个star,谢谢!