请注意,实例字典已被修改,尽管这通常没有必要,因为类字典已经包含相同的分配。因此,这个细节几乎不会被注意到 - 除非你 foo.bar = [] 事后再做。由于上述事实,实例保持 bar 不变。
在 class 中 foo2 ,类的属性 bar 被使用,但不会被触及。相反,类的属性 [x] 被添加到类中,形成一个新对象,正如 self.bar.__add__([x]) 这里所称,它不会修改对象。然后将结果放入实例字典中,将新列表作为字典提供给实例,而类的属性保持修改状态。
和 ... = ... + ... 之间的区别 ... += ... 也会影响之后的分配:
f = foo(1) # adds 1 to the class's bar and assigns f.bar to this as well.
g = foo(2) # adds 2 to the class's bar and assigns g.bar to this as well.
# Here, foo.bar, f.bar and g.bar refer to the same object.
print f.bar # [1, 2]
print g.bar # [1, 2]
f.bar += [3] # adds 3 to this object
print f.bar # As these still refer to the same object,
print g.bar # the output is the same.
f.bar = f.bar + [4] # Construct a new list with the values of the old ones, 4 appended.
print f.bar # Print the new one
print g.bar # Print the old one.
f = foo2(1) # Here a new list is created on every call.
g = foo2(2)
print f.bar # So these all obly have one element.
print g.bar