class A(object):
def foo(self,x):
print "executing foo(%s,%s)"%(self,x)
@classmethod
def class_foo(cls,x):
print "executing class_foo(%s,%s)"%(cls,x)
@staticmethod
def static_foo(x):
print "executing static_foo(%s)"%x
a=A()
a.foo(1)
a.class_foo(2)
a.static_foo(3)
print '--------'
A.class_foo(4)
A.static_foo(5)
print '--------'
print a.foo
print a.class_foo
print a.static_foo
executing foo(<__main__.A object at 0x106ad2190>,1)
executing class_foo(<class '__main__.A'>,2)
executing static_foo(3)
--------
executing class_foo(<class '__main__.A'>,4)
executing static_foo(5)
--------
<bound method A.foo of <__main__.A object at 0x106ad2190>>
<bound method type.class_foo of <class '__main__.A'>>
<function static_foo at 0x106ad1500>
解析
對象方法只能用類的實(shí)例對象調(diào)用,A.foo(1)會(huì)報(bào)錯(cuò),對象方法默認(rèn)將對象實(shí)體a傳遞給方法的第一個(gè)參數(shù)(self);
類方法默認(rèn)傳遞給第一個(gè)參數(shù)的是類(class A),通常用變量cls表示,而不是self。類方法既可以用類名調(diào)用也可以用類的實(shí)例調(diào)用。
以上所說默認(rèn)傳遞第一個(gè)參數(shù),為什么呢?
a.foo 僅僅需要一個(gè)參數(shù),是因?yàn)閒oo函數(shù)默認(rèn)是綁定到a這個(gè)對象上的
print a.foo
<bound method A.foo of <__main__.A object at 0x106ad2190>>
a.class_foo 是A綁定到class_foo而不是 a;
最后剩下靜態(tài)方法,說到底它就是一個(gè)方法.a.static_foo只是返回一個(gè)不帶參數(shù)綁定的方法.static_foo和a.static_foo只需要一個(gè)參數(shù).
print a.static_foo
<function static_foo at 0x106ad1500>