Python global variable in class | Example code

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 and suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.