
目前在自学python,我通过设计两个类,然后再继承另一个的属性,但是具体的操作不清楚,求解
# 定义 Weapon 类
class Weapon:
def __init__(self, weight, firepower, price, anti_strike):
self.weight = weight # 重量
self.firepower = firepower #
self.price = price # 价格
self.anti_strike = anti_strike # 抗击打力
# 定义 Tank 类,继承 Weapon 类
class Tank(Weapon):
def __init__(self, weight, firepower, price, anti_strike, oil_consumption, speed, health):
super().__init__(weight, firepower, price, anti_strike) # 调用父类构造函数
self.oil_consumption = oil_consumption # 单位里程耗油量
self.speed = speed # 移动速度
self.health = health # 健康程度
def BeHit(self, strike_force):
# 计算受到的损伤
damage = strike_force / self.anti_strike
self.health -= damage
def ShowState(self):
# 显示对象状态
print("重量:", self.weight)
print("火---力:", self.firepower)
print("价格:", self.price)
print("抗击打力:", self.anti_strike)
print("单位里程耗油量:", self.oil_consumption)
print("移动速度:", self.speed)
print("健康程度:", self.health)
# 创建 Tank 对象
my_tank = Tank(2000, 800, 500000, 600, 10, 50, 100)
# 受到火--力为 20000 的打击
my_tank.BeHit(20000)
# 显示受--打--击后对象的状态
my_tank.ShowState()