I got the code below from an exam and I don't understand why the first time when you make f2 = f1
, doing f1.set()
changes f2
but after that when you set f1 = Foo("Nine", "Ten")
doesn't change f2
at all. If anyone knows why please explain it to me. Thank you so much!
Code:
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
Outcome:
['Four', 'Five', 'Six']
['Four', 'Five', 'Six']
['Nine', 'Ten', 3]
['Four', 'Five', 'Six']
['Eleven', 'Twelve']
['Four', 'Five', 'Six']