3

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']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

5
f2 = f1

After this statement both f1 and f2 are references to the same instance of Foo. Therefore, a change in one will effect the other.

f1 = Foo("Nine", "Ten")

After this, f1 is assigned to a new Foo instance so f1 and f2 are no longer connected in any way - so a change in one will not effect the other.

arshajii
  • 127,459
  • 24
  • 238
  • 287