如何在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']
我希望列表里能包含类的属性值。
2 个回答
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']
4
使用 getattr
函数
members = [getattr(self, attr) for attr in dir(self) if not attr.startswith("__")]
getattr(self, 'attr')
和 self.attr
是一样的意思