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.

Answer from unwind on Stack Overflow
🌐
WsCube Tech
wscubetech.com › resources › python › global-variable
Global Variable in Python: Explained With Examples
February 10, 2026 - Learn about global variables in Python with examples in this tutorial. Understand how to use and manage them effectively in your Python code.
Top answer
1 of 7
156

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.

2 of 7
26

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.

Discussions

Global variables in python classes
#1 Why this code returns name 'y' is not defined Because y is not defined in the enclosing scope. The "enclosing scope" for the line print(y) is the print_me() method. is it possible to add something like global or public tag to variables in python? Yes, you can tell Python that you want to use y from the Test() class scope like this: class Test: y = 1 def __init__(self): self.__x = 1 def print_me(self): print(Test.y) t = Test() t.print_me() #2 Why this code returns paradoxical response Test2.test() takes 0 positional arguments but 1 was given? Because the method test() is passed the instance object, but the self parameter is missing. In other words, Test2.test() is written with 0 positional arguments, but calling t2.test() automatically passes t2 as the self argument (t2 is the "1 [argument that] was given`). #3 Why class methods can define class variables in python? Class methods do not "define" class variables. Class methods can "access" class variables, using the cls parameter to represent the class object. More on reddit.com
🌐 r/learnpython
10
0
July 10, 2024
Painful details of variable scope mixed with classes
I’m revisiting variable scope technicalities in Python for my personal interpreter project. Some time ago, I asked about that and got the tip that CPython has a multi-pass system that figures out variables, scopes, and bindings ahead of generating byte code. More on discuss.python.org
🌐 discuss.python.org
0
0
July 29, 2022
How to make variables global by default, Python 3.11
I have Python 3.11 on Windows 10 Pro. I’m still a bit new to Python but I’m learning. In Python 3.11 the variables declared in the main program are not global by default and I cannot use them in functions. So if I want to use them in a function I have to use the global prefix/keyword. More on discuss.python.org
🌐 discuss.python.org
0
0
June 10, 2024
Global variable vs a Global variable instantiated as an instance of a class
I wouldn’t do either of these things. Part of why you use a class is to encapsulate state. When you call a method on a class, all you’re doing is calling a function with the instantiated class object being passed as the first argument…which is passing in the state of the object into your function for context. You can do this with any other variables or dependencies. Look up “dependency injection”. When you call a function, you pass in the dependancies as arguments. This decouples your code and helps prevent using globals. More on reddit.com
🌐 r/learnpython
14
3
February 2, 2024
People also ask

How do I make a global variable in Python?
To make a global variable, just define it at the top level of your script. For example, x = 10. Now you can access this x inside and outside of functions.
🌐
wscubetech.com
wscubetech.com › resources › python › global-variable
Global Variable in Python: Explained With Examples
What is a global variable in Python, and why do I need it?
A global variable in Python is one you define outside any function. You use it when you want the same variable to be accessed or shared across multiple functions in your code.
🌐
wscubetech.com
wscubetech.com › resources › python › global-variable
Global Variable in Python: Explained With Examples
What is variable scope in Python?
Variable scope is the area in which parts of a program can access the variable. In Python, there are four variable scopes:LocalGlobalEnclosingBuilt-in
🌐
wscubetech.com
wscubetech.com › resources › python › global-variable
Global Variable in Python: Explained With Examples
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-variables
Python Variables - GeeksforGeeks
Python variables hold references to objects, not the actual objects themselves. Reassigning a variable does not affect other variables referencing the same object unless explicitly updated.
Published   2 weeks ago
🌐
W3Schools
w3schools.com › python › python_variables_global.asp
Python - Global Variables
Global variables can be used by everyone, both inside of functions and outside. Create a variable outside of a function, and use it inside the function · x = "awesome" def myfunc(): print("Python is " + x) myfunc() Try it Yourself »
🌐
Programiz
programiz.com › python-programming › global-keyword
Python Global Keyword (With Examples)
In Python, the global keyword allows us to modify the variable outside of the current scope.
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › global variables in python classes
r/learnpython on Reddit: Global variables in python classes
July 10, 2024 -

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?

Top answer
1 of 3
3
#1 Why this code returns name 'y' is not defined Because y is not defined in the enclosing scope. The "enclosing scope" for the line print(y) is the print_me() method. is it possible to add something like global or public tag to variables in python? Yes, you can tell Python that you want to use y from the Test() class scope like this: class Test: y = 1 def __init__(self): self.__x = 1 def print_me(self): print(Test.y) t = Test() t.print_me() #2 Why this code returns paradoxical response Test2.test() takes 0 positional arguments but 1 was given? Because the method test() is passed the instance object, but the self parameter is missing. In other words, Test2.test() is written with 0 positional arguments, but calling t2.test() automatically passes t2 as the self argument (t2 is the "1 [argument that] was given`). #3 Why class methods can define class variables in python? Class methods do not "define" class variables. Class methods can "access" class variables, using the cls parameter to represent the class object.
2 of 3
2
For 1. when you access a free variable (i.e. one that's not a parameter to the function, or defined inside the function) then Python looks for that variable in the enclosing scopes. In Python this order goes, roughly: local -> non-local (outer enclosing function) -> non-local (next outer function) etc -> globals -> built-ins, skipping over the classes entirely. This is simply a language design question, and you need to access class and instance attributes through self in Python. For 2. When you call a method then Python calls the classes function passing the object as the self argument. So if Foo is the class, then foo.bar() is the same as Foo.bar(foo). So your code t2.test() is actually going Test2.test(t2) so you get the error. You can make these so-called "static" methods with the @staticmethod decorator. If you put @staticmethod on the line before the def test(): then your code will work, as a staticmethod disables this implicit passing of self. Although, in Python (unlike in say, Java), you can just put functions outside the class and so static methods are less common. For 3. I'm not really sure what the question is... But, Python basically has no restrictions on "who" can assign attributes. So anyone can put an attribute on an object from anywhere in the code if it has a reference to that object.
🌐
PythonHello
pythonhello.com › fundamentals › python-global-variables
Python Global Variables
In Python, a global variable is a variable that is defined outside of any function or class and is available for use throughout the entire program.
🌐
Real Python
realpython.com › python-use-global-variable-in-function
Using and Creating Global Variables in Your Python Functions – Real Python
December 8, 2024 - Creating global variables inside a function is possible using the global keyword or globals(), but it’s generally not recommended. Strategies to avoid global variables include using constants, passing arguments, and employing classes and methods ...
🌐
Simplilearn
simplilearn.com › home › resources › software development › python global variables | definition, scope and examples
Python Global Variables | Definition, Scope and Examples
September 9, 2025 - Python global variables explained! Learn how to declare, modify and use them effectively while understanding their scope, limitations and best practices.
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
Python documentation
docs.python.org › 3 › tutorial › modules.html
6. Modules — Python 3.14.3 documentation
Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode). A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__.
🌐
GeeksforGeeks
geeksforgeeks.org › python › global-local-variables-python
Global and Local Variables in Python - GeeksforGeeks
Inside function: Python is awesome! Outside function: Python is awesome! Explanation: msg is a global variable accessible both inside and outside the display() function.
Published   September 20, 2025
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
It is important to realize that scopes are determined textually: the global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias the function is called. On the other hand, the actual search for names is done dynamically, at run time — however, the language definition is evolving towards static name resolution, at “compile” time, so don’t rely on dynamic name resolution! (In fact, local variables are already determined statically.)
🌐
W3Schools
w3schoolsua.github.io › python › python_variables_global_en.html
Python Global Variables. Lessons for beginners. W3Schools in English
If you use the global keyword, the variable belongs to the global scope: def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) Try it Yourself »
🌐
Great Learning
mygreatlearning.com › blog › it/software development › global variables in python
Global Variables in Python
August 15, 2024 - In Python, a global variable is a variable that is defined outside of any function or class, making it accessible from anywhere within the program.
🌐
freeCodeCamp
freecodecamp.org › news › python-global-variables-examples
Python Global Variables – How to Define a Global Variable Example
May 12, 2022 - So, when I first try to print the value of the variable and then re-assign a value to the variable I am trying to access, Python gets confused. The way to change the value of a global variable inside a function is by using the global keyword:
🌐
Google
developers.google.com › google for education › python
Google's Python Class | Python Education | Google for Developers
The first exercises work on basic Python concepts like strings and lists, building up to the later exercises which are full programs dealing with text files, processes, and http connections. The class is geared for people who have a little bit of programming experience in some language, enough to know what a "variable" or "if statement" is.
🌐
Python.org
discuss.python.org › python help
Painful details of variable scope mixed with classes - Python Help - Discussions on Python.org
July 29, 2022 - I’m revisiting variable scope technicalities in Python for my personal interpreter project. Some time ago, I asked about that and got the tip that CPython has a multi-pass system that figures out variables, scopes, and bindings ahead of generating byte code.
🌐
TutorialsPoint
tutorialspoint.com › how-do-i-declare-a-global-variable-in-python-class
How do I declare a global variable in Python class?
April 30, 2025 - A global variable that is declared inside the class can be accessed inside and outside the class, and it can be modified within the class using the global keyword.
🌐
Python.org
discuss.python.org › python help
How to make variables global by default, Python 3.11 - Python Help - Discussions on Python.org
June 10, 2024 - I have Python 3.11 on Windows 10 Pro. I’m still a bit new to Python but I’m learning. In Python 3.11 the variables declared in the main program are not global by default and I cannot use them in functions. So if I want to use them in a function I have to use the global prefix/keyword.
🌐
Intellipaat
intellipaat.com › home › blog › how to use a global variable in a function in python?
How to Use a Global Variable in a Function in Python? - Intellipaat Blog
May 26, 2025 - ... Explanation: Environment variables are accessed through os.environ, and here, ‘GLOBAL_VAR’ is defined as 18 to 25. Global variables can be defined as class variables and then accessed through the class or an instance.