我不是很明白,下面例子中类属性integer和list的区别是什么:
class MyClass(object):
a = [1]
b = 1
def __init__(self):
print(self.a, id(MyClass.a))
print(self.b, id(MyClass.b))
def modify(self):
self.a.append(2)
print("modfied list attribute:", MyClass.a, id(MyClass.a))
print("modfied listattribute:", self.a, id(self.a))
self.b += 1
print("modfied int attribute:", MyClass.b, id(MyClass.b))
print("modfied int attribute:", self.b, id(self.b))
x = MyClass()
x.modify()
y = MyClass()
在此示例的输出中,您可以看到,如果我在一个实例 (x) 中更改列表,MyClass 中的实际属性也会更改。然而,当在一个实例中更改时,整数对于类保持不变。我假设,这与列表的特性有关,即如果附加了某些值,id 将保留。
谁能简要地给我一个简短的解释,这种行为背后的主要原因是什么?
最佳答案
int
值是不可变的。您没有修改现有的 int
,而是用 不同 int
值替换了 self.b
。
list
值是可变的,list.append
修改调用它的实例。 self.a
被就地修改,没有用新列表替换现有列表。
基本上,如果不知道使用它的值的类型,就无法预测 +=
的行为。在 b = 0; b += 1
,b
指的是 int
的新实例。但是在 b = []; b += [2,3]
,现有列表被扩展(就像您调用了 b.extend([2,3])
)。
关于python - 列为类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58288543/