我从一次考试中得到了下面的代码,但我不明白为什么第一次执行
f2 = f1
时,执行 f1.set()
会改变 f2
的值,但之后当你执行 f1 = Foo("Nine", "Ten")
时,却不会对 f2
产生影响。如果有人知道原因,请解释一下。谢谢!class Foo():
def __init__(self, x=1, y=2, z=3):
self.nums = [x, y, z]
def __str__(self):
return str(self.nums)
def set(self, x):
self.nums = x
f1 = Foo()
f2 = Foo("One", "Two")
f2 = f1
f1.set(["Four", "Five", "Six"])
print f1
print f2
f1 = Foo("Nine", "Ten")
print f1
print f2
f1.set(["Eleven", "Twelve"])
print f1
print f2
结果:
['Four', 'Five', 'Six']
['Four', 'Five', 'Six']
['Nine', 'Ten', 3]
['Four', 'Five', 'Six']
['Eleven', 'Twelve']
['Four', 'Five', 'Six']