How can I access global variable inside class in Python
You need to move the global
declaration inside your function:
class TestClass():
def run(self):
global g_c
for i in range(10):
g_c = 1
print(g_c)
The statement tells the Python compiler that any assignments (and other binding actions) to that name are to alter the value in the global namespace; the default is to put any name that is being assigned to anywhere in a function, in the local namespace. The statement only applies to the current scope.
Since you are never assigning to g_c
in the class body, putting the statement there has no effect. The global
statement only ever applies to the scope it is used in, never to any nested scopes. See the global
statement documentation, which opens with:
The global statement is a declaration which holds for the entire current code block.
Nested functions and classes are not part of the current code block.
I'll insert the obligatory warning against using globals to share changing state here: don't do it, this makes it harder to reason about the state of your code, harder to test, harder to refactor, etc. If you must share a changing singleton state (one value in the whole program) then at least use a class attribute:
class TestClass():
g_c = 0
def run(self):
for i in range(10):
TestClass.g_c = 1
print(TestClass.g_c) # or print(self.g_c)
t = TestClass()
t.run()
print(TestClass.g_c)
Note how we can still access the same value from the outside, namespaced to the TestClass
namespace.
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.