好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

python面向对象的实例讲解

还是以上次的洗衣机例子:

 1 class Washer: 2     company='ZBL' 3     def __init__(self,water=10,scour=2): 4         self._water=water #不想让用户直接访问实例变量,可以标志成私有 5         self.scour=scour 6         self.year=2000#这是生产日期 7         #属性包装,将water属性包装成方法,用户使用water时实际是访问的方法 8     @staticmethod #定义一个静态方法 9     def spins_ml(spins):10         return spins*0.411         print('company:',Washer测试数据pany)12         #print('year:',self.year)#错误,静态方法不能使用实例属性13     14     @property15     def water1(self):#如果用户使用 实例.water相当于访问这个方法,而不是真的访问属性16         return self._water17     18     @water1.setter19     def water1(self,water):20         if 0<water<=500:21             self._water=water22         else:23             print('set Failure!')24     @property25     def total_year(self):26         return 2017-self.year27     28     def set_water(self,water):29         self.water=water        
30 31     def set_scour(self,scour):32         self.scour=scour        
33 34     def add_water(self):35         print('Add water:',self._water)36 37     def add_scour(self):38         print('Add scour:',self.scour)39 40     def start_wash(self):41         self.add_water()42         self.add_scour()43         print('Start wash...')44         45 if __name__=='__main__':46     print(Washer.spins_ml (8))47     w=Washer()48     print(w.spins_ml(8))49     w=Washer(200,Washer.spins_ml(8))50     w.start_wash() 

查看更多关于python面向对象的实例讲解的详细内容...

  阅读:52次