python - 如何在 Python 中访问类内的全局变量

标签 python scope global

我有这个:

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/

相关文章:

variables - tcl 中的变量作用域

spring - 了解 Spring 的自定义范围

javascript - 将变量添加到 jQuery $ 范围是明智的还是会污染它?

php - 检查 $_POST 是否为数组?

c++ - 使用 "new"的类作用域

Python matplotlib 等高线图对数色标

python - 加速 Pandas DataFrame 中的 curve_fit

python - 将函数内的元组转换为全局值

python - 如何规范化 4D numpy 数组?

python - PyQt/Qt Designer - 无需插件即可升级小部件的额外参数