@classmethod及@staticmethod方法淺析【python】

來源:互聯網
上載者:User

標籤:

目前對於python中@classmethod 類方法和@staticmethod靜態方法的有了一定的認識,之後有進一步的認識後繼續記錄。

@classmethod :是和一個class類相關的方法,可以通過類貨類執行個體進行調用,並將該class對象(不是class的執行個體對象)隱式地當作第一個參數傳入。

 

@staticmethod

:基本上和一個全域函數差不多,可以通過類或者類的執行個體對象進行調用,不會隱式地傳入任何參數。

 

區別

:類方法需要額外的類變數cls,調用類方法傳入的類變數cls是子類,而不是父類。類方法和靜態方法都可以通過類對象和類的執行個體對象訪問。

 

樣本如下:

 1 class Myclass(object): 2  3     var = "test for myclass" 4  5     @classmethod 6     def clsmethod(cls): 7         print cls.var 8  9     @staticmethod10     def sticmethod():11         print MyClass.var

  雖然兩者輸出結果相同但是類方法已經隱式地傳入了當前的類作為參數,可以直接調用類方法直接輸出,而靜態方法則需綁定。

  另外一個顯然的對比例子如下:

 1 class ParentClass(object): 2      3     var = "test for parent" 4  5     @classmethod 6     def clsmethod(cls): 7         print cls.var 8  9 class SubClass(ParentClass):10     11     var = "test for sub"

  此時ParentClass.clsmethod輸出為 “test for parent”,而Subclass.clsmethod輸出為“test for sub”,通過此比較很好的詮釋了@classmethod類方法隱式傳入的第一個參數是當前類,而不是父類。同時類方法操作的是class 類對象提供的內部資訊。而staticmethod可以作為一般的工具函數來使用。

 

@classmethod及@staticmethod方法淺析【python】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.