组团学

面向对象案例

阅读 (268831)

案例:人开枪射击子弹

一、分析

  • 人类

    类名: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()
需要 登录 才可以提问哦