복붙노트

[PYTHON] 파이썬에서 클래스의 모든 멤버 변수에 대해 루핑하기

PYTHON

파이썬에서 클래스의 모든 멤버 변수에 대해 루핑하기

반복 가능한 클래스의 모든 변수 목록을 어떻게 구합니까? 지역 주민 ()과 비슷하지만 수업에는 적합합니다.

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

해결법

  1. ==============================

    1.

    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']
    
  2. ==============================

    2.함수가없는 변수 만 사용하려면 다음을 사용하십시오.

    함수가없는 변수 만 사용하려면 다음을 사용하십시오.

    vars(your_object)
    
  3. ==============================

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

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

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

    함수를 걸러 낼 것이다.

  4. ==============================

    4.

    >>> 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 ()은 당신이 찾고있는 것입니다.

  5. ==============================

    5.이렇게하는 쉬운 방법은 클래스의 모든 인스턴스를 목록에 저장하는 것입니다.

    이렇게하는 쉬운 방법은 클래스의 모든 인스턴스를 목록에 저장하는 것입니다.

    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
    
  6. ==============================

    6.

        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
    
  7. from https://stackoverflow.com/questions/1398022/looping-over-all-member-variables-of-a-class-in-python by cc-by-sa and MIT license