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']
4

1 回答 1

5
f2 = f1

在此语句之后,f1f2都是对同一实例的引用Foo。因此,一个变化会影响另一个。

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

在此之后,f1被分配给一个 Foo实例,因此f1不再f2以任何方式连接 - 因此一个更改不会影响另一个。

于 2012-12-12T00:00:20.303 回答