下面為大家分享一篇對Python中的@classmethod用法詳解,具有很好的參考價值,希望對大家有所協助。一起過來看看吧
在Python物件導向編程中的類構建中,有時候會遇到@classmethod的用法。
總感覺有這種特殊性說明的用法都是進階用法,在我這個層級的水平中一般是用不到的。
不過還是好奇去查了一下。
大致可以理解為:使用了@classmethod修飾的方法是類專屬的,而且是可以通過類名進行調用的。為了能夠展示其與一般方法的差異,寫一段簡單的代碼如下:
class DemoClass: @classmethod def classPrint(self): print("class method") def objPrint(self): print("obj method") obj = DemoClass()obj.objPrint()obj.classPrint() DemoClass.classPrint()DemoClass.objPrint()
程式的執行結果如下:
grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$python classmethod.pyobj methodclass methodclass methodTraceback (mostrecent call last): File "classmethod.py", line 13, in<module> DemoClass.objPrint()TypeError: unboundmethod objPrint() must be called with DemoClass instance as first argument (gotnothing instead)grey@DESKTOP-3T80NPQ:/mnt/e/01_workspace/02_programme_language/03_python/03_OOP/2017/08$exitexit E:\01_workspace\02_programme_language\03_python\03_OOP\2017\08>pythonclassmethod.pyobj methodclass methodclass methodTraceback (mostrecent call last): File "classmethod.py", line 13, in<module> DemoClass.objPrint()TypeError:objPrint() missing 1 required positional argument: 'self'
上面的程式執行,我是在兩個作業系統中的兩個Python版本環境中進行的。不管是Py2還是Py3,這方面的設計都是差不多的。總體來說,這種用法還是很微妙的。由於沒有足夠的實戰曆練,暫時還說不好這個東西有什麼更好的優勢。