Building on this question looping over all member variables of a class in python
Regarding how to iterate over a class' attributes / non functions. I want to loop over the class variable values and store in a list.
class Baz:
a = 'foo'
b = 'bar'
c = 'foobar'
d = 'fubar'
e = 'fubaz'
def __init__(self):
members = [attr for attr in dir(self) if not attr.startswith("__")]
print members
baz = Baz()
Will return ['a', 'b', 'c', 'd', 'e']
I would like the class attribute values in the list.
Use the getattr function
members = [getattr(self, attr) for attr in dir(self) if not attr.startswith("__")]
getattr(self, 'attr') is equivalent of self.attr
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