Skip to content

How to access class variable in Python | Example code

  • by

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 or suggestions on this Python variables 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