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
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)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With