如何解决GameCharacter() takes no arguments报错问题
问题分析与修复方案
错误点说明
- 构造函数命名错误:Python类的构造函数必须是
__init__(前后各两个下划线),你写的_init_(前后各一个下划线)无法被识别为构造函数,创建实例时传入的参数会因不匹配默认无参构造函数而报错。 - 实例化代码缩进错误:
game_character = GameCharacter('Rick', 5, 100)缩进在了类内部,会在类定义阶段就执行,既不符合逻辑,还会提前触发构造函数相关的错误,需将其移到类外部。
修正后的完整代码
class GameCharacter: def __init__(self, name, x_pos, health): self.name = name self.x_pos = x_pos self.health = health def move(self, by_amount): self.x_pos += by_amount def take_damage(self, amount): self.health -= amount if self.health < 0: self.health = 0 def check_is_dead(self): return self.health <= 0 # 实例化代码移至类外部 game_character = GameCharacter('Rick', 5, 100) print(game_character.name)
运行修正后的代码会正常输出Rick,类的其他方法也能按预期执行。
内容的提问来源于stack exchange,提问作者Agnideep Ghorai
相关产品推荐
相关产品推荐

