Ubuntu下Python编程:Pylance提示score未定义问题求助
问题解决方法
你的代码存在两个核心问题:
- 方法内直接使用
score会被Python判定为局部变量,而你未在方法内提前定义该变量,因此触发“score未定义”的报错。类属性的访问需要明确指定所属的类。 - 方法名设为
score会与类属性score重名,导致类属性被方法覆盖,后续无法正常访问。
修改后的代码示例:
class BowlingGame(): score = 0 def roll(self, points): # 明确访问类属性 BowlingGame.score += points # 修改方法名,避免与类属性重名 def get_score(self): return BowlingGame.score
如果希望通过实例访问类属性,也可以使用self.__class__.score,这种方式在子类继承时能自动适配对应子类的类属性:
class BowlingGame(): score = 0 def roll(self, points): self.__class__.score += points def get_score(self): return self.__class__.score
注意:类属性是所有实例共享的,若创建多个BowlingGame实例,它们会共用同一个score值。如果需要每个实例拥有独立的分数,还是得使用实例属性(即你之前尝试的构造函数方式)。
内容的提问来源于stack exchange,提问作者Juang
相关产品推荐
相关产品推荐

