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

2.1k Views Asked by At

I want to find an instance of a class, where an attribute has a certain value:

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)
2

There are 2 best solutions below

5
FLab On BEST ANSWER

From your example it looks like you are mixing two things: defining a Frame object (which contains an image) and defining a collection of Frames (which contains multiple frames, indexed so you can access them as you prefer).

So it looks like a xy problem: you probably just need to save Frame instances in a dictionary/list type of collection and then access the Frame you need.

Anyway, you can access the value of an attribute of an object using 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)
1
Ma0 On

Assuming this class:

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

and two instances:

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

You can find the one with idx=1 like so:

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']

Note that if you have a big code with lots of objects created in memory, gc.get_objects() will be big and thus this approach rather slow and inefficient. The gc.get_objects() idea I got from here.

Does this answer your question?