如何避免实例之间共享类数据? [英] How to avoid having class data shared among instances?

查看:52
本文介绍了如何避免实例之间共享类数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要的是这种行为:

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?

推荐答案

您想要这样做:

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

在类声明中声明变量使它们成为类成员,而不是实例成员。在 __ init __ 方法中声明它们可以确保在对象的每个新实例旁边创建一个新的成员实例,这是您要寻找的行为。

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.

这篇关于如何避免实例之间共享类数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆