python中类变量属性的循环

2024-06-02 09:27:40 发布

您现在位置:Python中文网/ 问答频道 /正文

基于这个问题 looping over all member variables of a class in 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']

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


Tags: of函数inself列表属性bazvariables
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']

{cd1>使用函数

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

getattr(self, 'attr')相当于self.attr

相关问题 更多 >