一般來說,要使用某個類的方法,需要先實例化一個對象再調用方法。
而使用@staticmethod或@classmethod,就可以不需要實例化,直接類名.方法名()來調用。
這有利於組織代碼,把某些應該屬於某個類的函數給放到那個類里去,同時有利於命名空間的整潔。
-
class A(object):
-
a = 'a'
-
-
def foo1(name):
-
print 'hello', name
-
def foo2(self, name):
-
print 'hello', name
-
-
def foo3(cls, name):
-
print 'hello', name
首先定義一個類A,類A中有三個函數,foo1為靜態函數,用@staticmethod裝飾器裝飾,這種方法與類有某種關系但不需要使用到實例或者類來參與。如下兩種方法都可以正常輸出,也就是說既可以作為類的方法使用,也可以作為類的實例的方法使用。
-
a = A()
-
a.foo1( 'mamq') # 輸出: hello mamq
-
A.foo1( 'mamq')# 輸出: hello mamq
foo2為正常的函數,是類的實例的函數,只能通過a調用。
-
a.foo2( 'mamq') # 輸出: hello mamq
-
A.foo2( 'mamq') # 報錯: unbound method foo2() must be called with A instance as first argument (got str instance instead)
foo3為類函數,cls作為第一個參數用來表示類本身. 在類方法中用到,類方法是只與類本身有關而與實例無關的方法。如下兩種方法都可以正常輸出。
-
a.foo3( 'mamq') # 輸出: hello mamq
-
A.foo3( 'mamq') # 輸出: hello mamq
但是通過例子發現staticmethod與classmethod的使用方法和輸出結果相同,再看看這兩種方法的區別。
既然@staticmethod和@classmethod都可以直接類名.方法名()來調用,那他們有什么區別呢
從它們的使用上來看,
@staticmethod不需要表示自身對象的self和自身類的cls參數,就跟使用函數一樣。
@classmethod也不需要self參數,但第一個參數需要是表示自身類的cls參數。
如果在@staticmethod中要調用到這個類的一些屬性方法,只能直接類名.屬性名或類名.方法名。
而@classmethod因為持有cls參數,可以來調用類的屬性,類的方法,實例化對象等,避免硬編碼。
也就是說在classmethod中可以調用類中定義的其他方法、類的屬性,但staticmethod只能通過A.a調用類的屬性,但無法通過在該函數內部調用A.foo2()。修改上面的代碼加以說明:
-
class A(object):
-
a = 'a'
-
-
def foo1(name):
-
print 'hello', name
-
print A.a # 正常
-
print A.foo2('mamq') # 報錯: unbound method foo2() must be called with A instance as first argument (got str instance instead)
-
def foo2(self, name):
-
print 'hello', name
-
-
def foo3(cls, name):
-
print 'hello', name
-
print A.a
-
print cls().foo2(name)