Python子类如何继承父类level变量以缩放health属性
问题分析与解决方案
核心问题
Stand类的构造函数未接收level参数,调用super().__init__(level, self, 0)时level变量未定义,直接报错。- 创建
Stand实例时,没有将所属Character的level传递进去,无法实现基于角色等级的属性动态缩放。 - 原代码中
super().__init__传入self作为stand参数,会导致Stand的stand属性指向自身,逻辑不合理。
修正方案(基于原继承设计)
调整类的构造函数,让level能从Character传递到Stand:
import random # --- Stand Battle Game --- # # --- Characters --- # class Character(): def __init__(self, level, stand, regenRate): self.level = level self.health = 100 + (10 * self.level) self.energy = 100 + (10 * self.level) self.stand = stand self.regen = regenRate # --- Characters --- # # --- Stands --- # class Stand(Character): def __init__(self, name, level): # Stand不需要拥有自己的Stand,故stand参数传None super().__init__(level, None, 0) self.name = name self.health = self.health * 10 self.energy = self.energy * 10 class TheWorld(Stand): def __init__(self, level): super().__init__("The World", level) class StarPlatinum(Stand): def __init__(self, level): super().__init__("Star Platinum", level) # --- Stands --- # # --- Game Function --- # def getStand(character, standList): if useArrow() is True and standChance() is True: # 创建Stand时传入角色的level selected_stand = standList[random.randint(0,len(standList)-1)](character.level) character.stand = selected_stand return "You have gained the stand: " + selected_stand.name def useArrow(): return input("You find a small stone arrowhead: A. Use B. Leave - ") == "A" def standChance(): return random.randint(1,3) == 1 # --- Game Function --- # playerCharacter = Character(0, None, 0) # 创建Dio时将自身level传给TheWorld Dio = Character(10, TheWorld(10), 10) # 调整standList为类,而非实例,方便后续动态传入level standList = [ TheWorld, StarPlatinum ] #getStand(playerCharacter, standList) print(Dio.stand.health) # 输出2000,符合(100+10*10)*10的预期
更合理的设计建议(取消继承)
从逻辑上来说,Character和Stand是拥有关系而非继承关系,单独设计Stand类会更清晰:
class Stand: def __init__(self, name, level): self.name = name self.health = (100 + 10 * level) * 10 self.energy = (100 + 10 * level) * 10 # 后续TheWorld、StarPlatinum的实现只需调整继承自Stand即可 class TheWorld(Stand): def __init__(self, level): super().__init__("The World", level)
这种设计避免了不必要的继承关系,代码逻辑更直观。
内容的提问来源于stack exchange,提问作者Cameron Hepburn
相关产品推荐
相关产品推荐

