Home >Backend Development >Python Tutorial >How Can I Prevent Shared Class Data Among Object Instances in Python?

How Can I Prevent Shared Class Data Among Object Instances in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 06:02:24377browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn