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

posted @ 2019-05-07 16:53  田玉斌  阅读(778)  评论(0编辑  收藏  举报