python學習之@classmethod @staticmethod

這個答案的原文是Difference between @staticmethod and @classmethod in Python

classmethod 與staticmethod非常類似,區別在於classmethod的第一個參數必須是類對象的引用,而staticmethod可以完全不帶參數。

Example:


解釋:

當class的定義只是簡單如下時:


我們想要解析格式如 11-09-2012類型的日期時,可以如下:


當需要處理的日期量變多時,我們希望對字符串格式日期的處理由類來完成,這樣邏輯變得簡單。

@classmethod方法可以派上用場,此時它相當於另一個構造函數,同樣返回Date實例


好處在於:

1.實現了date字符串在同一個地方解析,而且可重複調用

2.無論調用from_string函數的是實例還是類,第一個參數始終傳入的是類本身

@staticmethod 

裝飾的函數類似於c++中類的static函數, 只專屬於類,與類的實例沒有任何關係

第一篇博客,哈哈, 比較醜陋。。。。加油!!


參考:

https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner/12179752

https://www.zhihu.com/question/20021164








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章