简体   繁体   English

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

[英]How to iterate over class attributes but not functions and returning the attribute values in python?

Building on this question looping over all member variables of a class in python基于这个问题,在 python 中循环一个类的​​所有成员变量

Regarding how to iterate over a class' attributes / non functions.关于如何迭代类的属性/非函数。 I want to loop over the class variable values and store in a list.我想遍历类变量值并存储在列表中。

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()

Will return ['a', 'b', 'c', 'd', 'e']将返回['a', 'b', 'c', 'd', 'e']

I would like the class attribute values in the list.我想要列表中的类属性值。

Use the getattr function使用getattr函数

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

getattr(self, 'attr') is equivalent of self.attr getattr(self, 'attr')相当于self.attr

Use the getattr method:使用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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM