我有一个列表作为python类中的实例变量。对此列表的直接分配很好,但是附加到列表将全局更改它(即,跨该类的所有实例)。这是一个简单的例子:
class foo(object):
def __init__(self, x = []):
if not isinstance(x, list):
raise TypeError('x must be a list')
else:
self.x = x
f1 = foo()
f2 = foo()
f1.x = [1,2]
print 'f1.x', f1.x,' f2.x = ',f2.x
f3 = foo()
f4 = foo()
f3.x.append(2)
print 'f3.x = ',f3.x,' f4.x = ',f4.x
输出如下:
f1.x [1, 2] f2.x = []
f3.x = [2] f4.x = [2]
如何在追加时避免x中的全局变化?