如何计算自定义类的实例数? [英] How to count the number of instance of a custom class?

查看:62
本文介绍了如何计算自定义类的实例数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

SubBase1.py

from Base import Base

class SubBase1(Base):
    def __init__(self):
        Base.__init__(self)

SubBase2.py

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

What I should to do? Thank you very much at first! PS: environment: Ubuntu 14.04 + Python 3.4 + PyDev

推荐答案

cls上设置属性将在子类上设置 new 属性.您必须在以下Base上对此进行显式设置:

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

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

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

演示:

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

这篇关于如何计算自定义类的实例数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆