python面向对象讲解,python面向对象的实例讲解

0a982f74af5e3e5793038dfd0f96c853.png

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

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.company)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

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()

输出结果:

e87e62a0e2334d590a06fcdff54e237b.png

下面讲类方法:

d23f2fd17987c2ccd029cffc80f7a9a1.png

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.company)12 #print('year:',self.year)#错误,静态方法不能使用实例属性13 @classmethod14 def get_washer(cls,water,scour):#cls相当于实例方法中的self,调用是不用提供这个参数15 return cls(water,cls.spins_ml(scour))#cls代表类名Washer,故不是硬编码(改类名是不用改cls,若cls用类名代替也对,但若改类名这个地方也需要改动)16 17 @property18 def water1(self):#如果用户使用 实例.water相当于访问这个方法,而不是真的访问属性19 return self._water20 21 @water1.setter22 def water1(self,water):23 if 0

33 34 def set_scour(self,scour):35 self.scour=scour

36 37 def add_water(self):38 print('Add water:',self._water)39 40 def add_scour(self):41 print('Add scour:',self.scour)42 43 def start_wash(self):44 self.add_water()45 self.add_scour()46 print('Start wash...')47 48 if __name__=='__main__':49 ## print(Washer.spins_ml (8))50 ## w=Washer()51 ## print(w.spins_ml(8))52 ## w=Washer(200,Washer.spins_ml(8))53 ## w.start_wash()54 w=Washer.get_washer(100,9)#类名.类方法名55 w.start_wash()

fb6de8a6030f05f70c6b91be8f8a6023.png

-----------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值