# 属性方法:把一个方法变成一个静态属性 #1 class Dog(object): def __init__(self,name): self.name=name @property#属性 def eat(self):#不能传参数(见调用时为d1.eat,不用加括号) print('%s is eating %s'%(self.name,'肉')) def talk(self): print('吃饱了') d1=Dog('白蹄') d1.eat#不用加括号,加括号就错 d1.talk() #2 class Dog(object): def __init__(self,name): self.name=name @property def eat(self): print('%s is eating %s'%(self.name,'肉')) @property def talk(self,): print('吃饱了') @talk.setter def talk(self,food): print('set to food',food) d1=Dog('白蹄') d1.eat d1.talk d1.talk='包子' #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,'肉')) @property def talk(self,): print('%s吃%s嘛?'%(self.name,self.__food)) @talk.setter def talk(self,food): print('set to food',food) self.__food=food d1=Dog('白蹄') d1.eat d1.talk d1.talk='包子' d1.talk # del d1.talk出错,属性方法此种方式删不掉 #4 class Dog(object): def __init__(self,name): self.name=name self.__food=None @property def eat(self): print('%s is eating %s'%(self.name,'肉')) @property def talk(self,): print('%s吃%s嘛?'%(self.name,self.__food)) @talk.setter def talk(self,food): print('set to food',food) self.__food=food @talk.deleter def talk(self): del self.__food#删掉私有属性 print('删完了') d1=Dog('白蹄') d1.eat d1.talk d1.talk='包子' d1.talk del d1.talk # d1.talk出错,已经删除不能运行 #http://www.cnblogs.com/alex3714/articles/5213184.html