Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - class mutability

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']
like image 380
user1896235 Avatar asked Aug 05 '26 09:08

user1896235


1 Answers

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.

like image 88
arshajii Avatar answered Aug 06 '26 21:08

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!