Running the sample code below:
class S:
i = 0
a = []
def __init__(self):
self.i += 1
self.a.append(1)
s1 = S()
print((s1.i, s1.a))
s2 = S()
print((s2.i, s2.a))
The output will be:
(1, [1])
(1, [1, 1])
Why is int
S.i
reset to 0 for s2
but the list
S.a
does not reset to empty? I think it has something to do with the immutable int
vs mutable list
but could someone help to express more details what happened to the two class variables during the two init calls?
self.i += 1
is equivalent to
self.i = self.i + 1
When the instance variable does not exist, the value is looked up on the class, so in this scenario, it is equivalent to
self.i = S.i + 1
After you define self.i
, then any further value lookup is on the instance variable, not on the class variable. So after this line, you have S.i = 0
and s1.i = 1
. Since S.i
is not modified, s2.i
also becomes 1
.
On the other hand,
self.a.append(1)
does not create a new instance variable, but appends an element to the existing class variable.