如何遍历类属性而不是函数,并在python中返回属性值?

如何遍历类属性而不是函数,并在python中返回属性值?

问题描述:

以这个问题为基础 在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()

将返回['a', 'b', 'c', 'd', 'e']

我想要列表中的类属性值.

I would like the class attribute values in the list.

使用getattr函数

members = [getattr(self, attr) for attr in dir(self) if not attr.startswith("__")]

getattr(self, 'attr')等同于self.attr