Home >Backend Development >Python Tutorial >How to Prevent Class Data Sharing Between Instances in Python?

How to Prevent Class Data Sharing Between Instances in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 02:28:09366browse

How to Prevent Class Data Sharing Between Instances in Python?

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!

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