阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

面向对象案例

106次阅读
没有评论

共计 1718 个字符,预计需要花费 5 分钟才能阅读完成。

案例:人开枪射击子弹

一、分析

  • 人类

     类名:Person
    属性:gun  bulletBoxList
    行为:fire()  downBulletBox() upBulletBox()  reloadBullet()
    
  • 枪类

     类名:Gun
    属性:bulletBox
    行为:shoot()
    
  • 弹夹类

     弹夹
    类名:BulletBox
    属性:count  bulletList
    行为:
  • 子弹类

     子弹
    类名:Bullet
    属性:kj
    行为:

二、实现

  • 子弹类(bullet.py)

    class Bullet(object): def __init__(self, kj): self.kj = kj
  • 弹夹类(bulletBox.py)

    class BulletBox(object): def __init__(self, count): self.count = count self.bulletList = []
  • 枪类(gun.py)

    class Gun(object): def __init__(self): self.bulletBox = None def shoot(self): if len(self.bulletBox.bulletList) == 0: print("没有子弹了,请更换弹夹!") else: self.bulletBox.bulletList.pop() print("剩余 %d 发子弹"%len(self.bulletBox.bulletList))
  • 人类(person.py)

    from bullet import Bullet class Person(object): def __init__(self, gun, bulletBoxList): self.gun = gun self.bulletBoxList = bulletBoxList def fire(self): if not self.gun.bulletBox: print("请添加弹夹!") else: self.gun.shoot() def downBulletBox(self): # 没有子弹的弹夹 temp = self.gun.bulletBox self.gun.bulletBox = None return temp def upBulletBox(self, bulletBox): self.gun.bulletBox = bulletBox def reloadBullet(self, bulletBox, count): for i in range(count): # 创建子弹 bullet = Bullet(7.62) bulletBox.bulletList.append(bullet)
  • 主文件(main.py)

    from person import Person from gun import Gun from bulletBox import BulletBox def main(): # 创建一把枪 gun = Gun() # 创建 5 个弹夹 bulletBoxList = [] for i in range(5): bulletBox = BulletBox(7) bulletBoxList.append(bulletBox) # 创建一个人 per = Person(gun, bulletBoxList) # 让人给每个弹夹都上满子弹 for bulletBox in per.bulletBoxList: per.reloadBullet(bulletBox, bulletBox.count) # 找一个弹夹上到枪中 bulletBox = per.bulletBoxList[0] per.upBulletBox(bulletBox) per.fire() per.fire() per.fire() per.fire() per.fire() per.fire() per.fire() per.fire() # 没子弹,卸载弹夹 bulletBox = per.downBulletBox() # 给这个单击在填满子弹 per.reloadBullet(bulletBox, bulletBox.count) # 找一个弹夹上到枪中 bulletBox = per.bulletBoxList[2] per.upBulletBox(bulletBox) print("-------") per.fire() if __name__ == "__main__": main()

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-05-26发表,共计1718字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中