python中对于类内部定义的方法,分为三种,实例方法(对象方法)、类方法、静态方法
实例方法在被调用时,首先是需要以 obj.fun的方式调用,在调用的时候会偷偷传进去一个self。在定义时,需要在参数列表里写self,操作的变量的生命周期也是与此对象生命周期一致,并不能操作类下的属性(如下面代码中的aa),实际表现是操作无效,cls.aa还会被视为self.aa,如__init__
类方法在被调用时,首先是需要以 class.fun的方式调用,在调用的时候会向fun偷偷传进去一个cls。
静态方法可以由类名或对象名进行调用
class A():
aa=1
def __init__(cls,a):
cls.aa=a
@classmethod
def detect1(cls):
print(cls.aa)
@staticmethod
def detect2(cls):
print(cls.aa)
def detect3(self):
print(self.aa)
def detect4(cls):
print(cls.aa)
@classmethod
def detect5(self):
print(self.aa)
@classmethod
def set_clsattr(cls,a):
cls.aa=a
if __name__=='__main__':
oa=A(a=10)
print(oa.aa) #10
print(A.aa)# 1
oa.detect3() #10
oa.detect4() #10
#由上方5行代码可见。obj.fun调用时,会向fun偷偷传进一个self,即使形参是cls,传入的实参也是self
A.detect1() #1
A.set_clsattr(2)
print(A.aa) #2
A.detect1() #2
A.detect5() #2
#由上方5行代码可见。obj.fun调用时,会向fun偷偷传进一个self,即使形参是self,传入的实参也是cls
A.detect2(A) #2
A.detect2(oa) #10
oa.detect2(A) #2
oa.detect2(oa)#10
#由上方4行代码可见,调用静态方法时,不取决于谁调用,取决于传入什么参数
A.detect3() #detect3() missing 1 required positional argument: 'self'
#由上方1行代码可见,不能cls.fun调用实例方法