參考連結:https://blog.csdn.net/sinat_34079973/article/details/53502348
一般來說,調用某個類的方法,需要先生成一個執行個體,再通過執行個體調用方法。Java中有靜态變量,靜态方法,可以使用類直接進行調用。Python提供了兩個修飾符@staticmethod @classmethod也可以達到類似效果。
@staticmethod 聲明方法為靜态方法,直接通過 類||執行個體.靜态方法()調用。經過@staticmethod修飾的方法,不需要self參數,其使用方法和直接調用函數一樣。
#直接定義一個test()函數
def test():
print "i am a normal method!"
#定義一個類,其中包括一個類方法,采用@staticmethod修飾
class T:
@staticmethod
def static_test():#沒有self參數
print "i am a static method!"
if __name__ == "__main__":
test()
T.static_test()
T().static_test()
output:
i am a normal method!
i am a static method!
i am a static method!
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
@classmethod聲明方法為類方法,直接通過 類||執行個體.類方法()調用。經過@classmethod修飾的方法,不需要self參數,但是需要一個辨別類本身的cls參數。
class T:
@classmethod
def class_test(cls):#必須有cls參數
print "i am a class method"
if __name_ == "__main__":
T.class_test()
T().class_test()
output:
i am a class method
i am a class method
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
從上面的代碼片可以看出@staticmethod @classmethod的用法,引申出一個話題,Python定義函數時候是否需要self參數。
定義一個普通函數,不需要self參數
def test():
print "i am a test method!"
調用方法
test()
- 1
- 2
- 3
- 4
定義一個類的執行個體方法,需要self參數
不加self參數
class T:
def test():#不加self參數
print "i am a normal method!"
調用
t = T()
t.test()
output: #test()方法不需要參數,但是傳入了參數
Traceback (most recent call last):
File "F:/Workspace/test_script/test.py", line , in <module>
T().test()
TypeError: test() takes no arguments ( given)
實際上t.test() 調用方法為T.test(t)實際上是把執行個體當作參數傳給方法。故self方法不可缺失。
加self參數
class T:
def test(self):
print "self content is %s" % self
print "i am a normal method!"
調用
t = T()
t.test()
output:
self content is <__main__.T instance at >#self為T的執行個體
i am a test normal
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
定義一個類的靜态方法,不需要self參數
定義一個類方法,需要cls參數
小結:在Python中類和執行個體都是對象,都占用了記憶體空間,合理的使用@staticmethod @classmethod方法,就可以不執行個體化就直接使用類的方法啦~~
一般來說,調用某個類的方法,需要先生成一個執行個體,再通過執行個體調用方法。Java中有靜态變量,靜态方法,可以使用類直接進行調用。Python提供了兩個修飾符@staticmethod @classmethod也可以達到類似效果。