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


92

반복 가능한 클래스의 모든 변수 목록을 어떻게 얻습니까? 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

왜 사용할 수 for field in [ self.bool143, self.bool2, self.blah, self.foo, self.foobar2000 ]없습니까? 클래스의 인스턴스 변수를 모르는 경우 어떻게됩니까?
S.Lott

4
S.Lott : 그게 제가 어쨌든 한 일입니다. 실제 코드에는 40 개의 변수가 있으며 반복 목록을 수동으로 만들 필요가없는 것이 더 좋고 더 DRY라고 생각했습니다.
priestc

답변:


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

9
객체를 인스턴스화하는 이유 : 클래스 유형 대신 dir (Example ()) dir (예제)
Erdal

8
가치를 어떻게 얻습니까?
knutole

7
@knutole : getattr (object, attr)
opello 2014 년

8
어떻게 callable(attr)작동합니까? 되지는 attr문자열?
cubuspl42

6
dir은 ' 를 이름으로 만 반환하기 때문에 호출 가능 여부를 확인하려면 vars(Example).items()또는 vars(instance.__class__).items()대신 사용 했어야 합니다.dir()string
rrw

118

함수없이 변수 만 원하면 다음을 사용하십시오.

vars(your_object)

5
여전히 vars 를 필터링해야 하지만 이것이 정답입니다
gaborous

3
이 접근 방식은 예를 들어 네트워크를 통해 상태를 보내기 전에 직렬화 할 항목을 찾는 데 사용합니다.
Thom

7
vars클래스 변수는 포함 되지 않고 인스턴스 변수 만 포함됩니다.
DilithiumMatrix

2
@DilithiumMatrix 클래스 변수를 얻으려면 클래스 자체에서 vars (THECLASSITSELF)를 사용해야합니다. 아래에서 내 대답을 확인하십시오.
AmirHossein

2
이 방법을 사용하여 OP의 질문에 구체적으로 대답하십시오. members = list(vars(example).keys())as (적어도 python3에서는) 멤버 변수의 이름을 값에 매핑하는 것을 vars반환 dict합니다.
Michael Hall

28

@truppo : 귀하의 대답은 거의 정확하지만, callable은 문자열을 전달하기 때문에 항상 false를 반환합니다. 다음과 같은 것이 필요합니다.

[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")]

함수를 필터링합니다.


6
>>> a = Example()
>>> dir(a)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'bool143', 'bool2', 'blah',
'foo', 'foobar2000', 'as_list']

— 보시다시피 모든 속성 을 제공 하므로 약간 필터링해야합니다. 하지만 기본적으로 dir()당신이 찾고있는 것입니다.


-1
row2dict = lambda r: {c.name: str(getattr(r, c.name)) for c in r.__table__.columns} if r else {}

이것을 사용하십시오.


오해의 소지가 있습니다. 기본적으로 클래스 에는 ' table ' 속성이 없습니다 .
ben26941

-2
    class Employee:
    '''
    This class creates class employee with three attributes 
    and one function or method
    '''

    def __init__(self, first, last, salary):
        self.first = first
        self.last = last
        self.salary = salary

    def fullname(self):
        fullname=self.first + ' ' + self.last
        return fullname

emp1 = Employee('Abhijeet', 'Pandey', 20000)
emp2 = Employee('John', 'Smith', 50000)

print('To get attributes of an instance', set(dir(emp1))-set(dir(Employee))) # you can now loop over

-3

이 작업을 수행하는 쉬운 방법은 클래스의 모든 인스턴스를 list.

a = Example()
b = Example()
all_examples = [ a, b ]

물체는 저절로 존재하지 않습니다. 프로그램의 일부에서 이유가 있습니다. 창조는 이유가 있습니다. 목록에 수집하는 것도 이유가 있습니다.

공장을 사용하면 할 수 있습니다.

class ExampleFactory( object ):
    def __init__( self ):
        self.all_examples= []
    def __call__( self, *args, **kw ):
        e = Example( *args, **kw )
        self.all_examples.append( e )
        return e
    def all( self ):
        return all_examples

makeExample= ExampleFactory()
a = makeExample()
b = makeExample()
for i in makeExample.all():
    print i

아이디어가 마음에 듭니다 (실제로 현재 프로젝트에서 사용할 수 있습니다). 그러나 질문에 대한 답은 아닙니다. OP는 인스턴스 자체가 아니라 속성을 나열하려고합니다.
balpha 09.09.09

@balpha : 죄송합니다. 질문을 읽지 않았습니다. 90 %의 경우 "클래스의 모든 인스턴스를 찾는 방법"과 중복됩니다. 실제 질문 (이제 지적 했음)은 현명하지 않습니다. 인스턴스 변수를 알고 있습니다. 목록을 만드십시오.
S.Lott
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.