Skip to content

Python global variable in class | Example code

  • by

If a variable declared outside of the function or in global scope is called a global variable in Python. If it’s defined inside the class but not in any function then still it will available to other members.

Python global variable in class example

Simple example code Global variables can be used inside of functions and outside.

Defining it in the class: Simply assign a property to the class.

Using outside a variable inside the function.

class Foo(object):
    bar = 1

    def bah(self):
        print(self.bar)


f = Foo()
f.bah()

Output:

Python global variable in class

Using global Keyword

Local variable crate inside a function and it can only be used inside that function.

Using the keyword global before a variable makes this variable belongs to the global scope:

def myfunc():
    global var
    var = "Python"


myfunc()

print(var)

Output: Python

Do comment if you have any doubts or suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading