Python RPG游戏TypeError问题解决及代码优化咨询
Python RPG游戏TypeError错误修复与代码优化
错误原因
Monster类调用父类Person的构造函数时参数顺序错误,导致health属性被错误赋值为字符串类型,进而在is_dead函数中与整数0比较时触发TypeError: '<=' not supported between instances of 'str' and 'int'错误。
错误修复方案
- 修正子类(Monster、Wizard)的
super()调用,改用关键字参数传递参数,彻底避免参数顺序错误。例如Monster的构造函数修改为:super().__init__(name=name, max_health=max_health, health=health, max_mp=max_mp, mp=mp, magic=magic, magic_defe=magic_defe)
代码优化建议
- 类名遵循大驼峰命名规范,例如将
armor改为Armor、weapon改为Weapon - 修正
attack方法的逻辑错误:将条件判断改为attack_type == "magic" or attack_type == "m" - 修正
level_up方法的错误:将self.exp -= self.exp_to_next_lvl改为self.exp -= self.exp_to_next_lvl()(调用方法而非直接引用方法对象)
内容的提问来源于stack exchange,提问作者Help
相关产品推荐
相关产品推荐

