programing

python에서 클래스의 모든 멤버 변수를 루핑

subpage 2023. 9. 6. 22:06
반응형

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

함수 없이 변수만 사용하려면 다음을 사용합니다.

vars(your_object)

@japppo: 당신의 대답은 거의 맞지만, 당신이 단지 줄을 전달하는 것이기 때문에 callable은 항상 거짓으로 돌아올 것입니다.다음과 같은 것이 필요합니다.

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

기능들을 걸러낼 것입니다.

>>> 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()당신이 찾는 겁니다

와 유사합니다.vars(), 아래 코드를 사용하여 모든 클래스 속성을 나열할 수 있습니다.에 해당합니다.vars(example).keys().

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

이거 써요.

ClassName.__dict__["__doc__"]

함수, 내장 변수 등을 걸러내고 필요한 필드만 제공합니다!

이를 위한 쉬운 방법은 클래스의 모든 인스턴스를 저장하는 것입니다.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

언급URL : https://stackoverflow.com/questions/1398022/looping-over-all-member-variables-of-a-class-in-python

반응형