天天看點

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