作业一
士兵老Amy有一把枪(AK47),
士兵可以开火
枪能够发射子弹
枪能够添加子弹
枪类:
属性:型号,子弹数量
行为:发射子弹,添加子弹
士兵类:
属性:士兵名称,枪支
行为:开火行为(需考虑到:是否有枪支?以及添加子弹,发射子弹
class Gun(object):
def __init__(self, gun_type, gun_bullet):
self.type = gun_type
self.bullet = gun_bullet
def shooting(self, num_shots):
self.bullet -= num_shots
print(f"本次射出子弹:{num_shots}发, 剩余子弹{self.bullet}发")
if self.bullet < 1:
self.reload()
def reload(self):
self.bullet = 45
print(f"已重新装填弹药,当前子弹{self.bullet}发")
class Soldier(Gun):
def __init__(self, soldier_name, gun_type, gun_bullet):
self.name = soldier_name
super().__init__(gun_type, gun_bullet)
print(f"士兵姓名:{self.name}, 使用枪械:{self.type}, 初始弹药:{self.bullet}发")
def fire(self, num_shots):
super().shooting(num_shots)
War = Soldier('Amy', 'AK47', 45)
War.fire(1) # 点射
War.fire(3) # 连射3次
作业二
车类1:
属性:颜色,轮子个数(默认4个),重量级,速度(默认为0)
行为:加速,减速,停车
车类2:
属性:在基于车类1的基础上,添加一些比如:牌子,型号,空调系统等
行为:覆盖车类1的加速与减速,打印输出车辆信息
class CarType1:
def __init__(self, colour, lv_weight, tyre_num=4, speed=0):
self.colour = colour
self.weight = lv_weight
self.tyre = tyre_num
self.speed = speed
@staticmethod
def accelerate(self):
print("车类1加速")
@staticmethod
def decelerate(self):
print("车类1减速")
@staticmethod
def parking(self):
print("车类1停车")
class CarType2(CarType1):
def __init__(self, car_brand, car_type, car_air_conditioner, colour, lv_weight, tyre_num=4, speed=0):
self.car_brand = car_brand
self.type = car_type
self.air_conditioner = car_air_conditioner
super().__init__(colour, lv_weight, tyre_num, speed)
print(f"车辆品牌:{self.car_brand},车型号:{self.type},车颜色:{self.colour}"
f"车重:{self.weight},车空调:{self.air_conditioner},车轮子数:{self.tyre},车速度:{self.speed}")
def accelerate(self):
print("车类2加速")
def decelerate(self):
print("车类2减速")
car_infor = CarType2("宝马", "X5", "冷热空调", "蓝色", "2吨")
car_infor.accelerate()
car_infor.decelerate()