Avoiding class data shared among the instances in Python

When we create multiple instances of a class in Python, class variables are shared among all instances. This can lead to unexpected behavior when modifying mutable objects like lists or dictionaries. In this article, we will explore the problem and two effective solutions to avoid shared class data.

The Problem: Shared Class Variables

In the below example, we demonstrate how class variables are shared across all instances, leading to unintended data sharing ?

class MyClass:
    listA = []  # This is a class variable, shared by all instances

# Instantiate both classes
x = MyClass()
y = MyClass()

# Manipulate both instances
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)

# Print Results
print("Instance X:", x.listA)
print("Instance Y:", y.listA)
Instance X: [10, 20, 30, 40]
Instance Y: [10, 20, 30, 40]

As we can see, both instances share the same list, which is usually not the desired behavior.

Solution 1: Using __init__ Method

We can use the __init__ method to create instance variables instead of class variables. Each instance gets its own copy of the variable ?

class MyClass:
    def __init__(self):
        self.listA = []  # This creates an instance variable

# Instantiate both classes
x = MyClass()
y = MyClass()

# Manipulate both instances
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)

# Print Results
print("Instance X:", x.listA)
print("Instance Y:", y.listA)
Instance X: [10, 30]
Instance Y: [20, 40]

Solution 2: Reassigning Variables After Instantiation

In this approach, we reassign the variables after creating instances. This creates instance-specific variables that override the class variable ?

class MyClass:
    listA = []  # Class variable

# Instantiate both classes
x = MyClass()
y = MyClass()

# Reassign to create instance variables
x.listA = []
y.listA = []

# Manipulate both instances
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)

# Print Results
print("Instance X:", x.listA)
print("Instance Y:", y.listA)
Instance X: [10, 30]
Instance Y: [20, 40]

Comparison of Methods

Method Advantages Disadvantages
Using __init__ Clean, automatic, follows Python conventions Requires modifying class definition
Variable reassignment Can be applied to existing classes Manual process, easy to forget

Conclusion

Use the __init__ method to create instance variables for the cleanest solution. Variable reassignment works but requires manual intervention for each instance. Always prefer instance variables over class variables for mutable data.

Updated on: 2026-03-15T18:17:48+05:30

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements