python靜態方法怎么使用self
python-靜態方法,類方法,屬性方法
靜態方法實際上與類(或者實例)沒有什么關系。
使用了靜態方法,則不能像實例方法那樣再使用self。
裝飾器
@staticmethod#靜態方法
@classmethod#類方法
@property#屬性方法
靜態方法可以使用類調用也可以使用對象調用:
classDog(object):
def__init__(self,name):
self.name=name
@staticmethod
defeat():
print("iseating")
#類調用
Dog.eat()
#對象調用
d=Dog('dog1')
d.eat()
靜態方法:
只是名義上歸類管理,實際上在靜態方法里面訪問不了類或者實例的任何屬性。一般不需要傳參數self。
類方法
只能訪問類變量,不能訪問實例變量。需要有self參數。
類方法的示例:
classDog(object):
food2="food2"
def__init__(self,name):
self.name=name
@classmethod
defeat(self):
print("iseating%s"%self.food2)
Dog.eat()
d=Dog('dog1')
d.eat()
或者這樣:
classDog(object):
food2="food2"
def__init__(self,name):
self.name=name
@classmethod
defeat(cls):
print("iseating%s"%cls.food2)
Dog.eat()
d=Dog('dog1')
d.eat()
屬性方法:
把一個方法變成一個靜態屬性。調用的時候不需要加()。使用屬性方法代替setter和getter方法
classDog(object):
def__init__(self,name):
self.name=name@property
defeat(self):
#print("Iameating")
return'eat'
defabc(self):
print('abc')d=Dog('xg')print(d.eat)
以上內容為大家介紹了python培訓之靜態方法怎么使用self,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。

相關推薦HOT
更多>>
python包的導入方式有幾種
python包的導入方式有幾種本文教程操作環境:windows7系統、Python3.9.1,DELLG3電腦。1、from...import導入frompackageimportmodule1,mo詳情>>
2023-11-08 23:58:44
python參數是什么
python參數是什么1、概念Python中函數的參數是不變的對象。Python函數具有靈活的參數形式,但默認參數必須指向不變的對象。如果默認參數是可變...詳情>>
2023-11-08 19:48:30
python使用items()遍歷鍵值對
python使用items()遍歷鍵值對字典可以用來存儲各種方式的信息,所以有很多方式可以通過字典的所有鍵值對、鍵或值。說明1、即使通過字典,鍵值對...詳情>>
2023-11-08 19:23:48
python按行讀取文件的方法比較
python按行讀取文件的方法比較1、read方法默認會把文件的所有內容一次性讀取到內存。如果文件太大,對內存的占用會非常嚴重2、readline方法,re...詳情>>
2023-11-08 18:22:27