How to access class variable in Python | Example code

Use class_name dot variable_name to access a class variable from a class method in Python. Use instance to access variables outside the class.

Example access a class variable in Python

Simple example code.

A class variable is a variable that is shared by all objects of the same class.

class Employee:
    branch = 'IT Branch'  # Class Variable

    def a_class_method():
        print(Employee.branch)


Employee.a_class_method()

Output:

How to access class variable in Python

How to access variables from a class in python

Print variable values.

class Example(object):
    msg = "Hello"


obj = Example()

print(obj.msg)
print(Example.msg)

Output:

Hello
Hello

Accessing class variables outside the class in Python

First, you need to create an instance of the class, then you can use that instance to access its instance variable and function.

class Example(object):
    var_msg = "Welcome"
    var_num = 100


obj_example = Example()

print(obj_example.var_msg)
print(obj_example.var_num)

Output:

Welcome
100

Do comment if you have any doubts and suggestions on this Python variables 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.