Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over class attributes but not functions and returning the attribute values in python?

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.

like image 962
Dap Avatar asked Nov 20 '25 21:11

Dap


1 Answers

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

like image 187
Ashoka Lella Avatar answered Nov 22 '25 11:11

Ashoka Lella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!