Class Variables and Object Variables in Python

In Python, class variables and object variables are used to store data related to classes and their instances. Understanding the distinction between these two types of variables is crucial for effective class design and object-oriented programming.

Class Variables

Class variables are variables that are shared among all instances of a class. They are defined within the class and are typically used for attributes that should have the same value for every object. Class variables are accessed using the class name or through instances of the class.

Key Features of Class Variables:

Object Variables

Object variables, also known as instance variables, are variables that are unique to each instance of a class. They are defined within methods (usually in the __init__() method) and are used to store data that is specific to each object.

Key Features of Object Variables:

Example of Class Variables and Object Variables

This example demonstrates the use of class variables and object variables in a class.

Code Example

class Dog:
            # Class variable
            species = "Canis familiaris"  # All dogs belong to this species
        
            def __init__(self, name, age):
                # Object variables
                self.name = name  # Unique to each dog
                self.age = age    # Unique to each dog
        
        # Creating instances of Dog class
        dog1 = Dog("Buddy", 3)
        dog2 = Dog("Max", 5)
        
        # Accessing class and object variables
        print(f"{dog1.name} is a {dog1.species} and is {dog1.age} years old.")
        print(f"{dog2.name} is a {dog2.species} and is {dog2.age} years old.")
        

Output

Buddy is a Canis familiaris and is 3 years old.
Max is a Canis familiaris and is 5 years old.

Conclusion

Understanding the difference between class variables and object variables is essential for effective class design in Python. Class variables provide shared attributes, while object variables allow for instance-specific data, promoting encapsulation and modularity in object-oriented programming.