靜態方法,類方法,屬性方法
阿新 • • 發佈:2017-07-31
ack posit elf none pre name n) nal last
1.靜態方法:只是名義上歸類管理,實際上在靜態方法裏訪問不了類或實例中的任何屬性。相當於類的工具包。
class Dog(object):
def __init__(self,name):
self.name=name
@staticmethod #實際上跟類沒什麽關系了,相當於一個獨立的函數。
def eat(self,food):
print("%s is eating %s"%(self.name,food))
def drink(self,food):
print("%s is drinking %s"%(self.name,food))
d1=Dog("Lily")
d1.drink("Cooola") #drink正常執行
d1.eat("baozi") #靜態方法
運行結果:
Traceback (most recent call last): File "<encoding error>", line 13, in <module> TypeError: eat() missing 1 required positional argument: ‘food‘ Lily is drinking Cooola
2.類方法只能訪問類變量,不能訪問實例變量。
class Dog(object): n=123 def __init__(self,name): self.name=name @classmethod #類方法,被修飾的下列函數只能訪問類變量,不能訪問實例變量。def eat(self,food): print("類變量%s" % self.n) print("%s is eating %s"%(self.name,food)) def drink(self,food): print("%s is drinking %s"%(self.name,food)) d1=Dog("Lily") d1.drink("Cooola") #drink正常執行 d1.eat("baozi") #類方法
運行結果:
Lily is drinking Cooola 類變量123 Traceback (most recent call last): File "<encoding error>", line 15, in <module> File "<encoding error>", line 8, in eat AttributeError: type object ‘Dog‘ has no attribute ‘name‘
3.屬性方法
把一個方法變成一個靜態屬性。隱藏實現細節。就不能加()調用了。給屬性方法賦值
class Dog(object): def __init__(self,name): self.name=name self.__food=None @property #屬性方法 def eat(self): print("%s is eating %s"%(self.name,self.__food)) @eat.setter def eat(self,food): print("set to food:",food) self.__food=food d=Dog("Lily") d.eat d.eat="baozi" #屬性方法 d.eat
運行結果:
Lily is eating None set to food: baozi Lily is eating baozi
4.屬性方法在實例中不能以del d.eat 的方式刪除。刪除方法如下:
class Dog(object): def __init__(self,name): self.name=name self.__food=None @property #把一個方法變成屬性 def eat(self): print("%s is eating %s"%(self.name,self.__food)) @eat.setter #修改它 def eat(self,food): print("set to food:",food) self.__food=food @eat.deleter #刪除它 def eat(self): del self.__food print("刪除完畢") d=Dog("Lily") d.eat d.eat="baozi" #屬性方法 d.eat del d.eat d.eat
運行結果:
Lily is eating None set to food: baozi Lily is eating baozi 刪除完畢 Traceback (most recent call last): File "<encoding error>", line 26, in <module> File "<encoding error>", line 9, in eat AttributeError: ‘Dog‘ object has no attribute ‘_Dog__food‘
靜態方法,類方法,屬性方法