Python中@classmethod和@staticmethod的區(qū)別
1.@classmethod
- class method是和類綁定的方法,不是和類的對(duì)象(實(shí)例)綁定的方法
- class method能夠訪問(wèn)類的狀態(tài),因?yàn)樗梢越邮芤粋€(gè)指向類的參數(shù)(cls),而不是指向類實(shí)例的參數(shù)(self)。
- class method可以修改類的狀態(tài),并應(yīng)用到所有的類實(shí)例上。
class C(object): @classmethod def fun(cls, arg1, arg2, ...): .... fun: function that needs to be converted into a class method returns: a class method for function.
2.@staticmethod
- class method也是和類綁定的方法,不是和類的對(duì)象(實(shí)例)綁定
- class method不能訪問(wèn)類的狀態(tài)
- class method存在于類中是因?yàn)樗且粋€(gè)相關(guān)的函數(shù)
class C(object): @staticmethod def fun(arg1, arg2, ...): ... returns: a static method for function fun.
3.例子
class A(object): value = 42 def m1(self): print(self.value) @classmethod def m2(cls): print(cls.value) cls.value += 10 @staticmethod def m3(cls_instance): cls_instance.value -= 10 #小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流群:531509025 a = A() # a.m1 # <bound method A.m1 of <__main__.A object at 0x7fc8400b7da0>> a.m1() # 42 # m1()是類A中的普通方法,必須在實(shí)例化的對(duì)象上進(jìn)行調(diào)用。如果使用直接A.m1()就會(huì)得到m1() missing 1 required positional argument: 'self'的錯(cuò)誤信息。
到此這篇關(guān)于Python中@classmethod和@staticmethod的區(qū)別的文章就介紹到這了,更多相關(guān)Python @classmethod和@staticmethod內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python標(biāo)準(zhǔn)庫(kù)中內(nèi)置裝飾器@staticmethod和@classmethod
- Python中類方法@classmethod和靜態(tài)方法@staticmethod解析
- Python?class類@staticmethod及@classmethod區(qū)別淺析
- 詳解python中@classmethod和@staticmethod方法
- 詳解Python中@staticmethod和@classmethod區(qū)別及使用示例代碼
- Python 類方法和實(shí)例方法(@classmethod),靜態(tài)方法(@staticmethod)原理與用法分析
相關(guān)文章
Python3.7 + Yolo3實(shí)現(xiàn)識(shí)別語(yǔ)音播報(bào)功能
這篇文章主要介紹了Python3.7 + Yolo3識(shí)別語(yǔ)音播報(bào)功能,開(kāi)始之前我們先得解析出來(lái)Yolo3的代碼,從而獲取到被識(shí)別出來(lái)的物體標(biāo)簽,具體詳細(xì)過(guò)程跟隨小編一起看看吧2021-12-12python書(shū)籍信息爬蟲(chóng)實(shí)例
這篇文章主要為大家詳細(xì)介紹了python書(shū)籍信息爬蟲(chóng)示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03Python修改文件往指定行插入內(nèi)容的實(shí)例
今天小編就為大家分享一篇Python修改文件往指定行插入內(nèi)容的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01Python利用Turtle繪畫(huà)簡(jiǎn)單圖形
這篇文章主要介紹了Python利用Turtle繪畫(huà)簡(jiǎn)單圖形,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07利用Python實(shí)現(xiàn)快速批量轉(zhuǎn)換HEIC文件
HEIC 是蘋(píng)果采用的新的默認(rèn)圖片格式,它能在不損失圖片畫(huà)質(zhì)的情況下,減少圖片大小。本篇文章將使用 Python 批量實(shí)現(xiàn) HEIC 圖片文件的格式轉(zhuǎn)換,需要的可以參考一下2022-07-07python ndarray數(shù)組對(duì)象特點(diǎn)及實(shí)例分享
在本篇文章里小編給大家分享的是一篇關(guān)于python ndarray數(shù)組對(duì)象特點(diǎn)及實(shí)例相關(guān)內(nèi)容,有需要的朋友們跟著學(xué)習(xí)下。2021-10-10