【问题标题】:How to iterate over class attributes but not functions and returning the attribute values in python?如何迭代类属性而不是函数并在python中返回属性值?
【发布时间】:2014-10-21 12:15:03
【问题描述】:

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

标签: python class loops variables


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用getattr 函数

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-04
      • 2015-11-17
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多