python - 如何迭代类属性而不是函数并在 python 中返回属性值?

标签 python class loops variables

基于这个问题 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']

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

最佳答案

使用getattr函数

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

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

关于python - 如何迭代类属性而不是函数并在 python 中返回属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25535156/

相关文章:

javascript - Base 64 字符串有时会神奇地变大......

python - 将随机值组附加到列表中 (Python)

python - 如何使用 SQLAlchemy 高效地进行批量插入或更新?

python - 延迟调用应该放在 gekko 代码中的什么位置?

java - 可以从 Java 类调用 servlet 吗?

javascript - 在 for 循环中运行类中的方法

java - 如何跳出嵌套循环

javascript - 如何将 utf-8 数据从 Django 传递到 javascript

C++在构造函数初始化列表中获取类成员地址

java - 写一个方法计算前n个奇数的和