定义两个类一个 Person 类一个 Gun 类。 Gun 里面有一个弹夹int 类的数组初始容量为 5还有一个装子弹的方法 push打出子弹的方法 pop。Person 类有一个实例方法 shoot 方法调用 Gun 中 方法 pop请用代码模拟一个人开枪射击的过程装填子弹装满了就不能再装填射击没子弹不能射击先装进的子弹先射击出去。
class Gun:
def __init__(self):
self.clip = [0] * 5 # 初始化弹夹,容量为5
self.bullet_count = 0 # 当前子弹数量
def push(self):
if self.bullet_count < 5: # 弹夹未满时才能装填
self.clip[self.bullet_count] = 1 # 装填子弹
self.bullet_count += 1 # 子弹数量加1
print("装填子弹")
else:
print("弹夹已满,无法再装填")
def pop(self):
if self.bullet_count > 0: # 有子弹时才能射击
self.clip[self.bullet_count - 1] = 0 # 打出子弹
self.bullet_count -= 1 # 子弹数量减1
print("射击")
else:
print("没有子弹,无法射击")
class Person:
def __init__(self):
self.gun = Gun() # 初始化一把枪
def shoot(self):
self.gun.pop() # 调用枪的射击方法
person = Person()
person.gun.push() # 装填子弹
person.shoot() # 射击
person.gun.push() # 装填子弹
person.gun.push() # 装填子弹
person.shoot() # 射击
person.shoot() # 射击
person.shoot() # 射击
person.shoot() # 射击
输出:
装填子弹
射击
装填子弹
装填子弹
射击
射击
射击
没有子弹,无法射击
``
原文地址: https://www.cveoy.top/t/topic/ic6P 著作权归作者所有。请勿转载和采集!