Avoiding class data shared among the instances in Python

PythonServer Side ProgrammingProgramming

When we instantiate a class in Python, all its variables and functions also get inherited to the new instantiated class. But there may be e occasions when we do not want some of the variables of the parent class to be inherited by the child class. In this article, we will explore two ways to do that.

Instantiation Example

In the below example we show how the variables are instance heated from a given class and how the variables are shared across all the instantiated classes.

 Live Demo

class MyClass:
   listA= []

# Instantiate Both the classes
x = MyClass()
y = MyClass()

# Manipulate both the classes
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)

Output

Running the above code gives us the following result −

Instance X: [10, 20, 30, 40]
Instance Y: [10, 20, 30, 40]

Private Class variable with __inti__

We can use the I need a method to make the variables inside a class as private. These variables will not be shared across the classes when the parent class is instantiated.

Example

 Live Demo

class MyClass:
   def __init__(self):
      self.listA = []

# Instantiate Both the classes
x = MyClass()
y = MyClass()

# Manipulate both the classes
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)

Output

Running the above code gives us the following result −

Instance X: [10, 30]
Instance Y: [20, 40]

By declaring variables outside

In this approach, we will re-declare the variables outside the class. As the variables get initialized again that do not get shared across the instantiated classes.

Example

 Live Demo

class MyClass:
   listA = []

# Instantiate Both the classes
x = MyClass()
y = MyClass()

x.listA = []
y.listA = []
# Manipulate both the classes
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)
Output

Output

Running the above code gives us the following result −

Instance X: [10, 30]
Instance Y: [20, 40]
raja
Published on 22-Jul-2020 07:55:10
Advertisements