class C:
def f1(self, n):
print(self, n)
return n
# 類方法對象
@classmethod
def f2(cls, n):
print(cls, n)
return n
@staticmethod
def f3(n):
print(n)
return n
if __name__ == "__main__":
c = C()
n = 1
c.f1(n)
C.f1(c, n)
foo = C.f1
foo(c, n)
c.f2(n)
C.f2(n)
bar = C.f2
bar(n)
c.f3(n)
C.f3(n)
f = C.f3
f(n)
執(zhí)行結(jié)果:
<__main__.C object at 0x0000021D54BD2828> 1
<__main__.C object at 0x0000021D54BD2828> 1
<__main__.C object at 0x0000021D54BD2828> 1
<class '__main__.C'> 1
<class '__main__.C'> 1
<class '__main__.C'> 1
1
1
1
結(jié)論
上面的方法其實本質(zhì)都是綁定在類上普通方法,只不過Python對不同的方法做了隱式傳參
@staticmethod 方法加缘,沒有隱式傳參
@classmethod 方法鸭叙,會隱式傳入類對象
實例方法,會傳入隱式實例對象