如何在 Python 中访问类内的全局变量 [英] How can I access global variable inside class in Python

查看:109
本文介绍了如何在 Python 中访问类内的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

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?

how can I actually modify my global variable g_c?

推荐答案

通过在访问它的函数中声明它global:

By declaring it global inside the function that accesses it:

g_c = 0

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print(g_c)

Python 文档 说到,关于global 声明:

全局语句是一个声明,适用于整个当前代码块.

The global statement is a declaration which holds for the entire current code block.

这篇关于如何在 Python 中访问类内的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆