Class Variables and Instance Variables in Python

Class variables and instance variables are two important concepts related to classes in Python. In this article, we will discuss class variable and instance variables with examples.

We can define empty class in Python as shown below

class Cat:
    pass

Two types of variables associated with a Python class – instance variables and class variables.

Instance variables

Instance variables are data unique to each instance of the the class. Let’s check the below example.

class Person:
    def __init__(self, name, age):
        self.name = name  #  instance variable
        self.age = age    #  another instance variable

Here name and age variables are unique to each instance of the class Person. The __init__ function is a constructor function, when we create an object of the class this function is called automatically.

p1 = Person("Tom",32)
p2 = Person("Jerry",25)

print(f"Name of person 1 : {p1.name}")
print(f"Name of person 2 : {p2.name}")

Output

Name of person 1 : Tom
Name of person 2 : Jerry

We can see that instance variables(name ,age) holds the data unique to each instance of the class.

Class variables

Class variables are unique to the class. Each instance of the class have this variable.

class Cat:
    kind = 'mammal'         # class variable shared by all instances
    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

Here we can see kind is class variable and all instance of class share this data.

cat1 = Cat("X")
cat2 = Cat("Y")

print(cat1.kind)
print(cat2.kind)

Output

mammal
mammal

Here cat1 and cat2 instances share the class variable “kind”.

Conclusion

In conclusion, all instances of the class shares class variables and instance variables are unique to each instance of the class.

Leave a Comment