How to avoid having class data shared among instan

2019-07-21 15:52发布

What I want is this behavior:

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, 3]
print(y.list) # prints [2, 4]

Of course, what really happens when I print is:

print(x.list) # prints [1, 2, 3, 4]
print(y.list) # prints [1, 2, 3, 4]

Clearly they are sharing the data in class a. How do I get separate instances to achieve the behavior I desire?

标签: python class
8条回答
Animai°情兽
2楼-- · 2019-07-21 16:28

To protect your variable shared by other instance you need to create new instance variable each time you create an instance. When you are declaring a variable inside a class it's class variable and shared by all instance. If you want to make it for instance wise need to use the init method to reinitialize the variable as refer to the instance

From Python Objects and Class by Programiz.com:

__init__() function. This special function gets called whenever a new object of that class is instantiated.

This type of function is also called constructors in Object Oriented Programming (OOP). We normally use it to initialize all the variables.

For example:

class example:
    list=[] #This is class variable shared by all instance
    def __init__(self):
        self.list = [] #This is instance variable referred to specific instance
查看更多
姐就是有狂的资本
3楼-- · 2019-07-21 16:29

You want this:

class a:
    def __init__(self):
        self.list = []

Declaring the variables inside the class declaration makes them "class" members and not instance members. Declaring them inside the __init__ method makes sure that a new instance of the members is created alongside every new instance of the object, which is the behavior you're looking for.

查看更多
登录 后发表回答