Reputation: 63
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 work. The following are the codes
Base.py
class Base:
## class members
__counter = int(0)
@classmethod
def _count(cls):
cls.__counter += 1
return cls.__counter
def __init__(self):
self.__id = self._count()
@property
def id(self):
return self.__id
SubBase1.py
from Base import Base
class SubBase1(Base):
def __init__(self):
Base.__init__(self)
SubBase2.py
from Base import Base
class SubBase2(Base):
def __init__(self):
Base.__init__(self)
main.py
from SubBase1 import SubBase1
from SubBase2 import SubBase2
s1 = SubBase1()
s2 = SubBase2()
print('s1-id', s1.id)
print('s2-id', s2.id)
The codes output:
s1-id 1
s2-id 1
But, what I want is:
s1-id 1
s2-id 2
What I should to do? Thank you very much at first! PS: environment: Ubuntu 14.04 + Python 3.4 + PyDev
Upvotes: 4
Views: 4872
Reputation: 1121486
Setting the attribute on cls
will set a new attribute on the subclasses. You'll have to explicitly set this on Base
here:
class Base:
__count = 0
@classmethod
def _count(cls):
Base.__count += 1
return Base.__count
def __init__(self):
self.__id = self._count()
@property
def id(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:
>>> class Base:
... __count = 0
... @classmethod
... def _count(cls):
... Base.__count += 1
... return Base.__count
... def __init__(self):
... self.__id = self._count()
... @property
... def id(self):
... return self.__id
...
>>> class SubBase1(Base): pass
...
>>> class SubBase2(Base): pass
...
>>> SubBase1().id
1
>>> SubBase1().id
2
>>> SubBase2().id
3
>>> SubBase2().id
4
Upvotes: 3