Python中的@classmethod

來源:互聯網
上載者:User
下面為大家分享一篇對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,這方面的設計都是差不多的。總體來說,這種用法還是很微妙的。由於沒有足夠的實戰曆練,暫時還說不好這個東西有什麼更好的優勢。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.