Skip to content

Python class variables | Basics

  • by

Python variable defines inside the class and which have the same value across all class instances is called class variables. A Class variable is declared when a class is being constructed. These variables are assigned a value at class declaration.

class MyClass:

    var = "Hello" #value shared across all class instances

Note: Modifying a class variable affects all objects instance at the same time.

Python class variables examples

Simple example code program to show that the variables with a value assigned in the class declaration, are class variables

class Employee:
    branch = 'IT'  # Class Variable

    def __init__(self, name, salary):
        self.name = name  # Instance Variable
        self.salary = salary  # Instance Variable


# Objects of Employee class
emp1 = Employee('John', 10000)
emp2 = Employee('Alen', 20000)

print(emp1.name, emp1.salary, emp1.branch)
print(emp2.name, emp2.salary, emp2.branch)

Output:

Python class variables

Why use class variables?

Answer: Python Class variables are useful because they allow you to declare a variable when a class has been built, which can then be used later in your class. They are not tied to any particular object of the class.

How to access a Class Variable in Python?

Answer: You can access it when we create an object of the class. Use this code to access the variables and print their value.

class MyClass:
    var = "Hello"


# Create object
obj = MyClass()

# Access variable
print(obj.var)

Output: Hello

Do comment if you have any doubts or suggestions on this Python basic topic.

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