
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Avoiding Class Data Shared Among Instances in Python
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.
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
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
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]