如何在 Python 中獲取給定類的所有例項的列表?
gc 或 weakref 模組用於獲取給定類的所有例項的列表。首先,我們將使用 pip 安裝 gc 模組 -
pip install gc
要使用 gc 模組,請使用 import -
import gc
使用 gc 模組獲取類的例項
在這個例子中,我們建立了一個 Demo 類,它有四個例項 -
ob1 = Demo() ob2 = Demo() ob3 = Demo() ob4 = Demo()
我們迴圈遍歷記憶體中的物件 -
for ob in gc.get_objects():
示例
使用 isinstance(),每個物件都檢查是否是 Demo 類的例項。讓我們看看完整的示例 -
import gc # Create a Class class Demo: pass # Four objects ob1 = Demo() ob2 = Demo() ob3 = Demo() ob4 = Demo() # Display all instances of a given class for ob in gc.get_objects(): if isinstance(ob, Demo): print(ob)
輸出
<__main__.Demo object at 0x000001E0A407FC10> <__main__.Demo object at 0x000001E0A407EBC0> <__main__.Demo object at 0x000001E0A407EBF0> <__main__.Demo object at 0x000001E0A407EC20>
使用 gc 模組顯示類的例項計數
示例
在這個例子中,我們將計算並顯示例項的計數 -
import gc # Create a Class class Demo(object): pass # Creating 4 objects ob1 = Demo() ob2 = Demo() ob3 = Demo() ob4 = Demo() # Calculating and displaying the count of instances res = sum(1 for k in gc.get_referrers(Demo) if k.__class__ is Demo) print("Count the instances = ",res)
輸出
Count the instances = 4
使用 weakref 模組顯示類的例項
weakref 模組也可以用來獲取類的例項。首先,我們將使用 pip 安裝 weakref 模組 -
pip install weakref
要使用 gc 模組,請使用 import -
import weakref
示例
現在讓我們看一個例子 -
import weakref # Create a Demo() function class Demo: instanceArr = [] def __init__(self, name=None): self.__class__.instanceArr.append(weakref.proxy(self)) self.name = name # Create 3 objects ob1 = Demo('ob1') ob2 = Demo('ob2') ob3 = Demo('ob3') # Display the Instances for i in Demo.instanceArr: print(i.name)
輸出
ob1 ob2 ob3
廣告