Home >Backend Development >Python Tutorial >How Can I Prevent Shared Class Data Among Object Instances in Python?
Preventing Shared Class Data Among Instances
In object-oriented programming, it's crucial to maintain distinct data for different instances of a class. However, by default, class-level variables are shared among all instances, which can lead to unexpected behaviors.
Understanding the Issue
Consider the following code:
class a: 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, 2, 3, 4] print(y.list) # prints [1, 2, 3, 4]
Instead of obtaining separate lists for x and y, both instances share the same list. This occurs because list is declared as a class variable, so all instances reference the same underlying object.
Solution: Instance Variables
To avoid shared data, instance variables should be utilized. Instance variables are defined within the constructor (__init__) of the class. Here's the corrected 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 case, the list attribute is initialized for each instance in the constructor, creating separate copies. The print statements now accurately reflect the intended behavior with distinct lists for x and y.
The above is the detailed content of How Can I Prevent Shared Class Data Among Object Instances in Python?. For more information, please follow other related articles on the PHP Chinese website!