1. 程式人生 > 實用技巧 >python 返回例項物件個數

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