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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3