如何计算自定义类的实例数?

时间:2014-08-31 09:30:02

标签: python python-3.x instance

我想在Python3.x中计算自定义类及其子类的实例数。怎么做?非常感谢你。

我尝试过类成员的方式,但它没有用。以下是代码

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)

代码输出:

s1-id 1
s2-id 1

但是,我想要的是:

s1-id 1
s2-id 2

我该怎么办?一开始非常感谢你! PS: 环境:Ubuntu 14.04 + Python 3.4 + PyDev

1 个答案:

答案 0 :(得分:2)

cls上设置属性将在子类上设置 new 属性。您必须在此处Base明确设置此内容:

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

如果您尝试在cls上设置属性,则每个类创建唯一的计数器,而不是与所有子类共享。

演示:

>>> 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