How to count the number of instance of a custom class?

不问归期 提交于 2019-12-02 03:39:35

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/25590649/how-to-count-the-number-of-instance-of-a-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!