Looping over class variable's attributes in python

陌路散爱 提交于 2019-12-25 03:54:31

问题


Building on this question looping over all member variables of a class in 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']

I would like the class attribute values in the list.


回答1:


Use the getattr function

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

getattr(self, 'attr') is equivalent of self.attr




回答2:


Use the getattr method:

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


来源:https://stackoverflow.com/questions/25535156/looping-over-class-variables-attributes-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!