面相对象程序设计中,类方法和静态方法是经常用到的两个术语。
逻辑上讲:类方法是只能由类名调用;静态方法可以由类名或对象名进行调用。
在C++中,静态方法与类方法逻辑上是等价的,只有一个概念,不会混淆。
而在Python中,方法分为三类实例方法、类方法、静态方法
class Test(object):
def InstanceFun(self): # 实例方法,传self,表示实例对象,只能通过实例调用
print("InstanceFun");
print(self);
@classmethod
def ClassFun(cls): # 类方法,传cls,表示类,只能通过类调用
print("ClassFun");
print(cls);
@staticmethod #静态方法,不传参,可以通过实例和类调用
def StaticFun():
print("StaticFun");
可以看到,在PYTHON中,两种方法的主要区别在于参数。实例方法隐含的参数为类实例self,而类方法隐含的参数为类本身cls。
静态方法无隐含参数,主要为了类实例也可以直接调用静态方法。
转载于:https://blog.51cto.com/woodcutter/1826685