Skip to content Skip to sidebar Skip to footer

How To Count The Number Of Instance Of A Custom Class?

I would like to count the number of instances of a custom class and its subclasses in Python3.x. How to do? Thank you very much. I have tried the way class-member, but it doesn't w

Solution 1:

Setting the attribute on cls will set a new attribute on the subclasses. You'll have to explicitly set this on Base here:

classBase:
    __count = 0    @classmethoddef_count(cls):
        Base.__count += 1return Base.__count

    def__init__(self):
        self.__id = self._count()

    @propertydefid(self):
        return self.__id

If you try and set the attribute on cls you create unique counters per class, not shared with all sub-classes.

Demo:

>>>classBase:...    __count = 0...    @classmethod...def_count(cls):...        Base.__count += 1...return Base.__count...def__init__(self):...        self.__id = self._count()...    @property...defid(self):...return self.__id...>>>classSubBase1(Base): pass...>>>classSubBase2(Base): pass...>>>SubBase1().id
1
>>>SubBase1().id
2
>>>SubBase2().id
3
>>>SubBase2().id
4

Post a Comment for "How To Count The Number Of Instance Of A Custom Class?"