python中的靜態方法和類方法

靜態方法實際上就是普通函數,定義形式是在def行前加修飾符@staticmethod,只是因爲某種緣由須要定義在類裏面。靜態方法的參數能夠根據須要定義,不須要特殊的self參數。能夠經過類名或者值爲實例對象的變量,已屬性引用的方式調用靜態方法函數

類方法定義形式是在def行前加修飾符@classmethod,這種方法必須有一個表示其調用類的參數,通常用cls做爲參數名,還能夠有任意多個其餘參數。類方法也是類對象的屬性,能夠以屬性訪問的形式調用。在類方法執行時,調用它的類將自動約束到方法的cls參數,能夠經過這個參數訪問該類的其餘屬性。一般用類方法實現與本類的全部對象有關的操做。spa

 1 ##coding:utf-8
 2 class TestClassMethod(object):
 3 
 4     METHOD = 'method hoho'
 5 
 6     def __init__(self):
 7         self.name = 'leon'
 8 
 9     def test1(self):
10         print 'test1'
11         print self
12 
13     @classmethod
14     def test2(cls):
15         print cls
16         print 'test2'
17         print TestClassMethod.METHOD
18         print '----------------'
19 
20     @staticmethod
21     def test3():
22         print TestClassMethod.METHOD
23         print 'test3'
24 
25 
26 a = TestClassMethod()
27 a.test1()
28 a.test2()
29 a.test3()
30 TestClassMethod.test3()
test1
<__main__.TestClassMethod object at 0x0000000003DDA5F8>
<class '__main__.TestClassMethod'>
test2
method hoho
----------------
method hoho
test3
method hoho
test3

實例方法隱含的參數爲類實例,而類方法隱含的參數爲類自己。
靜態方法無隱含參數,主要爲了類實例也能夠直接調用靜態方法。
因此邏輯上類方法應當只被類調用,實例方法實例調用,靜態方法二者都能調用。code

在貼一例,供參考:對象

 1 class TestClassMethod(object):
 2 
 3     METHOD = 'method hoho'
 4 
 5     def __init__(self):
 6         self.name = 'leon'
 7 
 8     def test1(self):
 9         print 'test1'
10         print self
11 
12     @classmethod
13     def test2(cls):
14         print cls
15         print 'test2'
16         print TestClassMethod.METHOD
17         print '----------------'
18 
19     @staticmethod
20     def test3():
21         print TestClassMethod.METHOD
22         print 'test3'
23 
24 
25 a = TestClassMethod()
26 a.test1()
27 a.test2()
28 a.test3()
29 TestClassMethod.test3()
test1
<__main__.TestClassMethod object at 0x0000000003DDA5F8>
<class '__main__.TestClassMethod'>
test2
method hoho
----------------
method hoho
test3
method hoho
test3
相關文章
相關標籤/搜索