Skip to main content
 首页 » 编程设计

python之防止成员对象引用同一个列表

2025年05月04日14lhb25

这应该很简单......

class Object: 
    x = 0 
    y = [] 
 
a = Object() 
b = Object() 
 
a.x = 1 
b.x = 2 
print a.x, b.x 
# output: 1 2 
# works as expected 
 
a.y.append(3) 
b.y.append(4) 
print a.y, b.y 
# output: [3, 4] [3, 4] 
# same list is referenced  how to fix? 
# desired output: [3] [4] 

据我所知,a.y 和 b.y 引用同一个列表。我怎样才能让他们分开?最好不要添加 __init__ 方法。

请您参考如下方法:

当您定义类时,您只创建了一次 y 的值。要为 y 的每个实例分配不同的列表,您确实需要一个 init 函数。只需将 self.y = [] 放入 __init__ 中,它就会按预期工作。