본문 바로가기
파이썬

파이썬에서 클래스의 모든 멤버 변수를 반복

by º기록 2021. 1. 31.
반응형

반복 가능한 클래스의 모든 변수 목록을 어떻게 얻습니까? locals ()와 비슷하지만 클래스

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

    def as_list(self)
       ret = []
       for field in XXX:
           if getattr(self, field):
               ret.append(field)
       return ",".join(ret)

이것은 반환되어야한다

>>> e = Example()
>>> e.as_list()
bool143, bool2, foo

 

해결 방법

 

dir(obj)

객체의 모든 속성을 제공합니다. 메서드 등에서 멤버를 직접 필터링해야합니다.

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

example = Example()
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print members   

당신에게 줄 것입니다 :

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']

 

참조 페이지 https://stackoverflow.com/questions/1398022

 

 

반응형

댓글