如何在 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 类的实例。让我们看看完整的示例 -

Open Compiler
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 模块显示类的实例计数

示例

在这个例子中,我们将计算并显示实例的计数 -

Open Compiler
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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

使用 weakref 模块显示类的实例

weakref 模块也可以用来获取类的实例。首先,我们将使用 pip 安装 weakref 模块 -

pip install weakref

要使用 gc 模块,请使用 import -

import weakref

示例

现在让我们看一个例子 -

Open Compiler
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

更新于: 2022-09-16

5K+ 浏览量

启动你的 职业生涯

通过完成课程获得认证

开始
广告