列为类属性 [英] List as class attribute
问题描述
我不完全了解,以下示例中的类属性整数或列表的区别是什么:
I do not fully understand, what the difference of class attribute integer or list in the following example is:
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仍会保留.
In the output of this example one can see, that if I alter the list in one instance (x), the actual atribute in MyClass is altered. The integer however when changed in one instance remains for the class the same. I assume, that this has to do with features of a list, i.e. that the id remains if some value is appended.
有人可以简要地给我一个简短的解释,这种行为背后的主要原因是什么?
Can someone give me a short explanation in a nutshell, what the main reason behind this behaviour is?
推荐答案
int
值是不可变的.您没有修改现有的 int
,而是将 self.b
替换为不同 int
值.
int
values are immutable. You didn't not modify an existing int
, but replaced self.b
with a different int
value.
list
值是可变的,而 list.append
修改调用它的实例. self.a
就地修改,而不用新列表替换现有列表.
list
values are mutable, and list.append
modifies the instance that invokes it. self.a
is modified in-place without replacing the existing list with a new one.
基本上,如果不知道 + =
的值类型,就无法预测其行为.在 b = 0;b + = 1
, b
指的是 int
的新实例.但是在 b = [];中b + = [2,3]
,则扩展了现有列表(就像您调用了 b.extend([2,3])
一样).
Basically, you cannot predict the behavior of +=
without knowing the type of the value using it. In b = 0; b += 1
, b
refers to a new instance of int
. But in b = []; b += [2,3]
, the existing list is extended (as if you had called b.extend([2,3])
).
这篇关于列为类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!