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:
Answer from unwind on Stack OverflowThe global statement is a declaration which holds for the entire current code block.
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.
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.
Global variables in python classes
Painful details of variable scope mixed with classes
How to make variables global by default, Python 3.11
Global variable vs a Global variable instantiated as an instance of a class
How do I make a global variable in Python?
What is a global variable in Python, and why do I need it?
What is variable scope in Python?
Videos
Hey this question have a few sub-questions:
#1 Why this code returns name 'y' is not defined is it possible to add something like global or public tag to variables in python?
class Test: y = 1 def __init__(self): self.__x = 1 def print_me(self): print(y) t = Test() t.print_me()
#2 Why this code returns paradoxical response Test2.test() takes 0 positional arguments but 1 was given?
class Test2: def test(): u = 5 t2 = Test2() t2.test()
#3 Why class methods can define class variables in python?