python 返回实例对象个数

对着背影说爱祢 提交于 2020-11-17 09:07:49

python 返回实例对象个数

Python 没有提供任何内部机制来跟踪一个类有多少个实例被创建了,或者记录这些实例是些什
么东西。如果需要这些功能,你可以显式加入一些代码到类定义或者__init__()和__del__()中去。
最好的方式是使用一个静态成员来记录实例的个数。靠保存它们的引用来跟踪实例对象是很危险的,
因为你必须合理管理这些引用,不然,你的引用可能没办法释放(因为还有其它的引用) ! 


class InstCt(object):
    count = 0
    def __init__(self):
        InstCt.count += 1     #千万不能用self.count + =1,因为这样统计的只是单个实例对象的
    def __del__(self):
        InstCt.count -= 1
    def howMany(self):
        print(InstCt.count)
        return InstCt.count

a = InstCt()
a.howMany()    #输出:1
b = InstCt()  
b.howMany()    #输出:2
c = InstCt()
c.howMany()    #输出:3
a.howMany()    #输出:3
b.howMany()    #输出:3
c.howMany()    #输出:3

print('================================')
del c
b.howMany()    #输出:2
del b
a.howMany()    #输出:1
del a
print('================================')
print(InstCt.count)    #输出:0

 

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