How to Isolate Class Data for Individual Instances
To avoid having class data shared among multiple instances and ensure each instance maintains its own data, follow these steps:
Declare Variables within the Constructor (__init__ Method)
Instead of declaring class-level variables outside of any method, define them within the init constructor method. For example:
class a: def __init__(self): self.list = [] # Declared within __init__ to create instance-specific lists
By initializing the list within __init__, a new instance of the list is created alongside each new instance of the object.
Sample Code:
class a: def __init__(self): self.list = [] x = a() y = a() x.list.append(1) y.list.append(2) x.list.append(3) y.list.append(4) print(x.list) # prints [1, 3] print(y.list) # prints [2, 4]
In this example, the list is no longer shared between the two instances (x and y), and each instance maintains its own separate data, as desired.
The above is the detailed content of How to Prevent Class Data Sharing Between Instances in Python?. For more information, please follow other related articles on the PHP Chinese website!