天天看点

python 类的例子题目描述源代码

题目描述

创建三个类:人类、枪类、弹夹类,实现人打枪,弹夹设置弹容量,随着子弹的减少显示弹夹内剩余子弹数

源代码

class People():
    def __init__(self,gun):
        self.gun = gun
    def fire(self):
        gun.shoot()

class Gun():
    def __init__(self,bulletBox):
        self.bulletBox = bulletBox
    def shoot(self):
        bulletBox.bulletNum -=1
        print("子弹剩余%d发" % bulletBox.bulletNum)
        if bulletBox.bulletNum == 0:
            print("没子弹了,请重新装弹")

class BulletBox():
    def __init__(self,bulletNum):
        self.bulletNum = bulletNum
bulletNum = int(input("请输入子弹个数:"))
if bulletNum >= 7:
    print("只能装填7发子弹")
else:
    bulletBox = BulletBox(bulletNum)
    gun = Gun(bulletBox)
    pro = People(gun)
    while 1:
        pro.fire()
        if bulletBox.bulletNum == 0:
            break
           

转载于:https://www.cnblogs.com/tianyb/p/10826305.html