I’m pretty new to programming and am having some trouble understanding the output of this code.
#testclass.py
class TestCount:
count = 0
def __init__(self):
self.attr1 = TestCount.count
self.attr2 = TestCount.count + 1
TestCount.count += 2
x = TestCount()
y = TestCount()
print(x.attr1, x.attr2)
print(y.attr1, y.attr2)
This is a rework of a larger example out of a book I’m currently learning out of. When this code is ran it gives:
0 1
2 3
When I expect it to be:
0 1
0 1
What is the fundamental that I’m missing here? I see y as a new instance but it seems to be picking up where x left off. Sorry if I’m not explaining myself clearly but I’m new at this.
countis a property of the class, not the instance. That means this value is shared by all instances.You are initializing
attr1withTestCount.countand later increasing it by2. So the second instance will start withattr1being set to2, for the third instance4, etc.If you want both properties (
attr1andattr2) to be initialized with0and1, you should do so:For ore information, I suggest to read the Classes section in the official Python tutorial.