How To Declare Global Variable in a Class | Python Class Global Variables

Python Class Global Variables :

Global Variables are those which can be accessed by the whole program.When we declare a variable in any class, that can be accessible in that particular class only.It doesn’t work out of the class.So If you want to access that class throughout the program we need to declare that variable as global.

To declare a Global Variable inside a class in Python, One should declare it in inside the scope of that class else that code might not work for you.

This is a Very Simple Script that I have taken from stack over flow to explain how it works.

This is the way one should declare global variable in a class to access it.

Python Class Global Variables

count = 0

#We should declare global variable inside function
class SampleClass():
    def run(self):
        global count
        for i in range(10):
            count = 1
            print count

For more details you can refer Python Documentation On Global Variables

Also Read : How To Make A Simple Python Chat Server 

If you have any doubts, please comment here 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *