I was looking at the Stack Overflow question Counting instances of a class?, and I'm not sure why that solution works and one using simple addition doesn't. I guess this is more of a question of how class vs. instance variables are stored and accessed.
Here's the code I think should work, but instead produces 4
for every id
:
class foo():
num = 3 # trying 3 instead of 0 or 1 to make sure the add is working
def __init__(self):
self.num += 1
self.id = self.num
f = foo()
g = foo()
print f.id # 4
print g.id # 4
The self.num +=1
statement is somewhat working (the addition is happening, but not the assignment).
What is happening under the hood that's making this assignment fail here, while the itertools.count
assignment succeeds in the other question's solution?