While working on a piece of code today I've found this somewhat surprising behavior and I'm looking for an explanation. See the following piece of code and output it produces
class Test:
t1 = []
t2 = 1
def xyz(self):
self.t1 += [1]
self.t2 += 1
for i in range(10):
v = Test()
v.xyz()
print(v.t1)
print(v.t2)
Output
[1]
2
[1, 1]
2
[1, 1, 1]
2
[1, 1, 1, 1]
2
[1, 1, 1, 1, 1]
2
[1, 1, 1, 1, 1, 1]
2
[1, 1, 1, 1, 1, 1, 1]
2
[1, 1, 1, 1, 1, 1, 1, 1]
2
[1, 1, 1, 1, 1, 1, 1, 1, 1]
2
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
2
My question is why it's somewhat inconsistent? It seems like t2 (int) gets reinitialized every time. On the other hand t1 (list) doesn't. According to documentation I'd assume t2 isn't reinitialized every time and should just be increased. Class properies should be shared among the instances of objects. What's exactly going on here?