Python - 根据属性值查找 class 的实例

Python - Find an instance of a class, based on a value of an attribute

我想找到一个 class 的实例,其中一个属性具有特定值:

import numpy as np
import inspect
import matplotlib.pyplot as plt

class Frame():
    def __init__(self, img, idx):
        self.image = img
        self.idx = idx

for i in range(10):
    img = np.random.randint(0, high=255, size=(720, 1280, 3), dtype=np.uint8) # generate a random, noisy image
    Frame(img, i)

# Pseudo Code below:
frame = inspect.getmembers(Frame, idx=5) # find an instance of a class where the index is equal to 5
plt.imshow(frame.img)

从您的示例来看,您似乎混合了两件事:定义一个 Frame 对象(其中包含一个图像)和定义一个 Frames 集合(其中包含多个帧,已编入索引以便您可以根据需要访问它们)。

所以它看起来像是一个 xy 问题:您可能只需要将 Frame 实例保存在 dictionary/list 类型的集合中,然后访问您需要的 Frame。

无论如何,您可以使用 getattr.

访问对象的属性值
all_frames = []

for i in range(10):
    img = np.random.randint(0, high=255, size=(720, 1280, 3), dtype=np.uint8) # generate a random, noisy image
    all_frames.append(Frame(img, i))

frames_to_plot = [frame for frame in all_frames if getattr(frame, index) == 5]

for frame in frames_to_plot:
    plt.imshow(frame.img)

假设这个 class:

class Frame():
    def __init__(self, img, idx):
        self.image = img
        self.idx = idx

和两个实例:

a = Frame('foo', 1)
b = Frame('bar', 2)

你可以像这样找到带有 idx=1 的那个:

import gc


def find_em(classType, attr, targ):
    return [obj.image for obj in gc.get_objects() if isinstance(obj, classType) and getattr(obj, attr)==targ]

print(find_em(Frame, 'idx', 1))  # -> ['foo']

请注意,如果您的代码很大且在内存中创建了很多对象,gc.get_objects() 会很大,因此这种方法相当缓慢且效率低下。我从 here.

得到的 gc.get_objects() 想法

这是否回答了您的问题?