2014-08-27 18 views
-1

大厦在这个问题上 looping over all member variables of a class in python循环执行类变量的值在Python

关于如何遍历一个类的变量。我想遍历类变量值并存储在一个列表中。

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']

我想在列表中的类属性值。

+0

使用'的理解内部getattr'。 – 2014-08-27 19:10:43

回答

2

使用getattr功能

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

getattr(self, 'attr')是等效的self.attr

2

使用GETATTR方法:

class Baz: 
    a = 'foo' 
    b = 'bar' 
    c = 'foobar' 
    d = 'fubar' 
    e = 'fubaz' 

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

baz = Baz() 
['foo', 'bar', 'foobar', 'fubar', 'fubaz']