I have a set of classes which should all keep track of which instance they are. For this purpose I have a class variable in the parent class, which is copied and incremented at initialization of each object. Here's a minimal example which seems to work just fine:
class Parent:
counter = 0
def __init__(self):
self.name = self.__class__.__name__ + "_" + str(self.__class__.counter)
self.__class__.counter += 1
def __repr__(self):
return self.name
mother = Parent()
father = Parent()
print(mother)
print(father)
Parent_0
Parent_1
So far so good. Now I'd like to use make some subclasses that have the same behavior without rewriting the code. So I do this:
class Child(Parent):
# counter = 0
pass
son = Child()
daughter = Child()
stepfather = Parent()
print(son)
print(daughter)
print(stepfather)
Child_2
Child_3
Parent_2
This behavior is not what I intended. When the first instance of a child is created it inherits whichever value the parent counter has at that moment, however after this the classes each maintain their own counter. I can avoid this by putting the line counter = 0 into every single subclass, but this strikes me as redundant. Is there some more elegant way that I can inherit the behavior from the parent without having to redeclare the same variable every time?