vermaete
vermaete

Reputation: 1373

Filter attributes of a class based on the type

I would like to filter the attributes of an object of a class based on their types.

The answer will be something around inspect, “list comprehensions”, type(), __dict__ and dict() but I don't get it working.

class A():
    def __init__(self, value):
        self.x = value

    def __str__(self):
        return "value = {}\n".format(self.x)

class T():
    def __init__(self):
        self.a1 = A(1)
        self.a2 = A(2)
        self.b = 4

t = T()

And I would like to print only the attributes of the type A in the class T

class T():
    def __init__(self):
        self.a1 = A(1)
        self.a2 = A(2)
        self.b = 4

    def __str__(self):
         ret = ""
         for i in [*magic*]:
             ret += str(i)
         return ret

Output should be something like:

value = 10
value = 15

Upvotes: 3

Views: 1217

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

You can use vars(self) to get a dictionary of the local attributes, then just test the values with isinstance():

def __str__(self):
    ret = ""
    for i in vars(self).values():
        if isinstance(i, A):
            ret += str(i)
    return ret

vars() essentially returns self.__dict__ here but is cleaner.

Turning this into a list comprehension for one-liner appeal:

def __str__(self):
    return ''.join([i for i in vars(self).values() if isinstance(i, A)])

Upvotes: 3

Related Questions