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

Python Button类__init__方法中无法修改类变量unq_number的问题

解决Python类变量修改时的「local variable referenced before assignment」错误

你在Pygame中编写Button类时,试图通过类变量unq_number给每个按钮分配唯一编号,但在__init__方法中直接执行unq_number += 1时触发报错,提示局部变量未定义就引用——这是因为Python对方法内变量的作用域判定规则导致的。

原问题代码

import pygame

class Button:
    unq_number = 0

    def __init__(self, text, bg_color, width, height, pos, gui_font):
        self.pressed = False

        # unique number for each button
        unq_number += 1
        self.unq_number = unq_number

        # Rectangle
        self.rect = pygame.Rect(pos, (width, height))
        self.bg_color = bg_color

        # text
        self.text_surf = gui_font.render(text, True, '#FFFFFF')
        self.text_rect = self.text_surf.get_rect(center=self.rect.center)

    def draw(self, surface, txt_color):
        pygame.draw.rect(surface, self.bg_color, self.rect)
        surface.blit(self.text_surf, self.text_rect)
        return self.check_click(txt_color)

    def check_click(self, txt_color):
        mouse_pos = pygame.mouse.get_pos()

        if self.rect.collidepoint(mouse_pos):
            self.bg_color = (0, 125, 110)

            if pygame.mouse.get_pressed()[0]:
                self.pressed = True
            else:
                if self.pressed == True:
                    self.pressed = False
                    return self.unq_number
        else:
            self.bg_color = txt_color

错误原因

Python中,当你在方法内对变量执行赋值操作(比如+=)时,会默认将该变量视为局部变量。unq_number += 1需要先读取变量值再修改,Python会优先在局部作用域查找unq_number,但局部并没有定义这个变量,因此触发报错。

修复方案

要修改类变量,必须明确指定它是类的属性,有两种常用方式:

方案1:直接通过类名访问类变量

修改__init__方法中编号相关的代码:

# unique number for each button
Button.unq_number += 1
self.unq_number = Button.unq_number

方案2:通过self.__class__访问类变量(推荐,适配子类继承场景)

如果后续需要继承Button类,用这种方式能自动适配子类的类变量:

# unique number for each button
self.__class__.unq_number += 1
self.unq_number = self.__class__.unq_number

两种方式都能正确修改类级别的unq_number,给每个按钮实例分配唯一的编号。

内容的提问来源于stack exchange,提问作者Abdul Rafey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:15:34