torayeff torayeff - 3 months ago 9
Python Question

How can I access global variable inside class in Python

I have this:

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


how can I actually modify my global variable g_c?

Answer

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

The Python documentation says this, about the global statement:

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