我有这个:
g_c = 0
class TestClass():
global g_c
def run(self):
for i in range(10):
g_c = 1
print(g_c)
t = TestClass()
t.run()
print(g_c)
我怎样才能真正修改我的全局变量 g_c?
最佳答案
通过在访问它的函数中声明它global
:
g_c = 0
class TestClass():
def run(self):
global g_c
for i in range(10):
g_c = 1
print(g_c)
Python documentation关于 global
声明这样说的:
The global statement is a declaration which holds for the entire current code block.
关于python - 如何在 Python 中访问类内的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10814452/