小编use*_*235的帖子

python - 类可变性

我从考试中得到了下面的代码,我不明白为什么你第一次做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
Run Code Online (Sandbox Code Playgroud)

结果:

['Four', 'Five', 'Six']
['Four', 'Five', 'Six']
['Nine', 'Ten', 3] …
Run Code Online (Sandbox Code Playgroud)

python class mutability

3
推荐指数
1
解决办法
76
查看次数

标签 统计

class ×1

mutability ×1

python ×1