You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu下Python编程:Pylance提示score未定义问题求助

问题解决方法

你的代码存在两个核心问题:

  1. 方法内直接使用score会被Python判定为局部变量,而你未在方法内提前定义该变量,因此触发“score未定义”的报错。类属性的访问需要明确指定所属的类。
  2. 方法名设为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:44:57