python基礎學習——靜態方法、類方法
阿新 • • 發佈:2018-10-09
記錄 ... details eba tro -i pos 不支持 --
最近溫故了一下 python 基礎知識,有新的理解,整理在此,以便以後查閱或糾正。
本文描述一下靜態方法和類方法,引出裝飾器的概念,在下一篇博文中記錄。
先舉例,看效果:
1 class MyClass:
2 def smeth():
3 print(‘This is a static method‘)
4 smeth = staticmethod(smeth)
5
6 def cmeth(cls):
7 print(‘This is a class method of‘, cls)
8 cmeth = classmethod(cmeth)
9
10 # 或用裝飾器
11 class MyClass:
12 @staticmethod
13 def smeth():
14 print(‘This is a static method‘)
15
16 @classmethod
17 def cmeth(cls):
18 print(‘This is a class method of‘, cls)
定義這些方法後,就可像下面這樣使用它們(無需實例化類):
In [24]: MyClass.smeth()
This is a static method
In [ 25]: MyClass.cmeth()
This is a class method of <class ‘__main__.MyClass‘>
上一篇文章提到的例子中出現的報錯,可以用類方法包裝一下消除,而用靜態方法不可,其實問題不是這樣的。
In [31]: class Foo:
...: @classmethod
...: def func(cls):
...: print(‘This is class method‘)
@staticmethod
def stat():
print(‘This is static method‘)
def cust(self):
print( ‘If you want to call me, write some agrs here‘)
In [32]: Foo.func()
This is class method
In [33]: Foo.stat()
This is static method
In [34]: Foo.cust()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-72-2f40225d37e1> in <module>()
----> 1 Foo.cust()
TypeError: cust() missing 1 required positional argument: ‘self‘
In [35]: Foo.cust(123)
If you want to call me, write some agrs here
之所以出現這種情況,就在於靜態方法和類方法創建的過程,它們分別包裝在 staticmethod 和 classmethod 類的對象中。
靜態方法的定義中沒有參數 self,可直接通過類來調用;
類方法的定義中包含類似於 self 的參數,通常被命名為 cls。對於類方法,也可通過對象直接調用,這時參數 cls 將自動關聯到類。
而普通的方法則需要傳遞一個 self 參數,否則就會報錯
說了這麽多,靜態方法和類方法在編程中起什麽作用,或是哪些情況下要用到它們?
我個人缺少編程的經驗,日常項目練習中也很少用到這個方法,所以只能拾人牙慧,摘錄如下:
在 Python 中,靜態方法和類方法以前一直都不太重要,主要是因為從某種程度上說,總是可以使用函數或關聯的方法替代它們,而且早期的 Python 版本並不支持它們。
因此,雖然較新的代碼沒有大量使用它們,但它們確實有用武之地(如工廠函數),因此你或許應該考慮使用它們。--摘自《python基礎教程第三版》
以下兩位博主的總結很清晰易懂,可做參考
Done博主 ITxiaoke博主
python基礎學習——靜態方法、類方法