我想跟蹤當前正在使用的某種類型的對象。例如:跟蹤一個類的所有實例或所有由元類創建的類。在Python中:如果僅在列表中引用對象,如何從列表中刪除對象?
這是很容易跟蹤的實例是這樣的:
class A():
instances = []
def __init__(self):
self.instances.append(self)
但是,如果一個實例是不是該列表將不再被需要之外的任何引用,我不想處理該實例中一個潛在的耗時循環。
我試圖刪除僅使用sys.getrefcount在列表中引用的對象。
for i in A.instances:
if sys.getrefcount(i) <=3: # in the list, in the loop and in getrefcount
# collect and remove after the loop
我遇到的問題是引用計數很模糊。 打開一個新的外殼和
sys.getrefcount(DummyClass)
另一個想法是複製的對象,然後刪除該對象已定於垃圾收集,並在最後一步刪除列表,並檢查創建一個沒有內容的回報5僞類那些對象。喜歡的東西:
Copy = copy(A.instances)
del A.instances
A.instances = [i for i in Copy if not copy_of_i_is_in_GC(i)]
的對象不必立即取出時引用計數爲0。我只是不想浪費對不再使用的對象太多ressources。
使用[弱引用](https://docs.python.org/3.5/library/weakref.html) – Barmar
http://stackoverflow.com/questions/12101958/keep-track-of-instances-in -python –
http://effbot.org/pyfaq/how-do-i-get-a-list-of-all-instances-of-a-given-class.htm –