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?
A global variable is a visible variable and can be used in every part of a program. Global variables are also not defined within any function or method. On the other hand, local variables are defined within functions and can only be used within those function(s).
You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword.
Rules of global keyword: If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global. Variables that are only referenced inside a function are implicitly global. We Use a global keyword to use a global variable inside a function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With