zoukankan      html  css  js  c++  java
  • python 返回实例对象个数

    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
  • 相关阅读:
    Python 魔法方法
    使用PHP7来批量更新MangoDB数据
    git 小乌龟安装教程
    webpack初学者(1)
    移动端与PC端的触屏事件
    解决onclick事件的300ms延时问题
    尺寸单位em,rem,vh,vw
    ngRoute 与ui.router区别
    angular.js的依赖注入解析
    ionic的基础学习(第一篇)
  • 原文地址:https://www.cnblogs.com/111testing/p/13986575.html
Copyright © 2011-2022 走看看