Skip to main content
 首页 » 编程设计

多个实例访问的Python类变量

2025年05月04日14傻小

我想定义一个全局变量,它可以被该类的所有实例访问(读取和写入)。我当前的解决方案如下例所示。我不喜欢在全局命名空间中使用变量,但我无法将 idx 放入类中。如何将 idx 放入类中并实现相同的效果?

# working 
idx = 0 
class test(object): 
    def add(self): 
        global idx 
        idx += 1 
    def print_x(self): 
        global idx 
        print(idx) 
 
test1 = test() 
test1.add() 
test1.print_x() 
test2 = test() 
test2.add() 
test2.print_x() 
 
# Error 
class test(object): 
    idx = 0 
    def add(self): 
        global idx 
        idx += 1 
    def print_x(self): 
        global idx 
        print(idx) 
 
test1 = test() 
test1.add() 
test1.print_x() 
test2 = test() 
test2.add() 
test2.print_x() 
 
Traceback (most recent call last): 
  File "test.py", line 16, in <module> 
    test1.add() 
  File "test.py", line 9, in add 
    idx += 1 
NameError: global name 'idx' is not defined 

请您参考如下方法:

您的代码失败是因为您试图在未正确声明的情况下访问全局变量 idx。您需要访问您的类变量。

class Test(object): 
    idx = 0 
    def add(self): 
        Test.idx += 1 
 
obj = Test() 
obj.add() 
print(Test.idx) 
obj = Test() 
obj.add() 
print(Test.idx) 

输出:

1 
2