programing

Python에서 객체의 속성을 열거하는 방법은 무엇입니까?

css3 2023. 6. 4. 22:28

Python에서 객체의 속성을 열거하는 방법은 무엇입니까?

IC# 우리는 반성을 통해 그것을 합니다.자바스크립트에서는 다음과 같이 간단합니다.

for(var propertyName in objectName)
    var currentPropertyValue = objectName[propertyName];

파이썬에서 어떻게 하나요?

for property, value in vars(theObject).items():
    print(property, ":", value)

일부 드문 경우에는 다음과 같은 경우가 있습니다.__slots__속성, 그러한 클래스는 종종 없습니다.__dict__.

dir() 간단한 방법입니다.다음을 참조:

Python Introspython 검사

참조.

이름별로 정렬된 (이름, 값) 쌍 목록에서 개체의 모든 멤버를 반환합니다.선택적인 조건부 인수를 제공하면 조건부가 참 값을 반환하는 멤버만 포함됩니다.

>>> [name for name,thing in inspect.getmembers([])]
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__',    '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', 
'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', 
'__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 
'insert', 'pop', 'remove', 'reverse', 'sort']
>>> 

__dict__개체의 속성은 정의된 다른 모든 속성의 사전입니다.Python 클래스는 getattr을 재정의하고 속성처럼 보이지만 존재하지 않는 것을 만들 수 있습니다.__dict__내장된 기능도 있습니다.vars()그리고.dir()미묘한 방식으로 다른 것들.그리고.__slots__대체할 수 있습니다.__dict__어떤 특이한 수업에서.

Python에서는 객체가 복잡합니다. __dict__반사식 프로그래밍을 시작하기에 적합한 장소입니다. dir()대화형 쉘에서 해킹을 하는 경우에는 여기서부터 시작해야 합니다.

한 줄기용:

print vars(theObject)

모든 속성의 반영을 찾고 있다면 위의 답변이 좋습니다.

단순히 사전의 키를 가져오려는 경우(파이썬의 '오브젝트'와는 다름),

my_dict.keys()

my_dict = {'abc': {}, 'def': 12, 'ghi': 'string' }
my_dict.keys() 
> ['abc', 'def', 'ghi']

이것은 다른 답들에 의해 완전히 다루어지지만, 저는 분명히 말할 것입니다.개체에는 클래스 특성과 정적 및 동적 인스턴스 특성이 있을 수 있습니다.

class foo:
    classy = 1
    @property
    def dyno(self):
        return 1
    def __init__(self):
        self.stasis = 2

    def fx(self):
        return 3

stasis정적입니다.dyno동적(특성 장식자) 및classy클래스 특성입니다.우리가 간단하게 한다면,__dict__또는vars우리는 정적인 것만 얻을 것입니다.

o = foo()
print(o.__dict__) #{'stasis': 2}
print(vars(o)) #{'stasis': 2}

그래서 만약 우리가 다른 사람들을 원한다면,__dict__모든 것을 얻게 될 것입니다.여기에는 매직 메소드 및 속성과 일반 바인딩 메소드가 포함됩니다.따라서 이러한 문제는 방지해야 합니다.

d = {k: getattr(o, k, '') for k in o.__dir__() if k[:2] != '__' and type(getattr(o, k, '')).__name__ != 'method'}
print(d) #{'stasis': 2, 'classy': 1, 'dyno': 1}

type속성 장식 메서드(동적 속성)와 함께 호출되면 반환된 값의 유형이 아니라method이를 증명하기 위해 json을 문자열화합니다.

import json
print(json.dumps(d)) #{"stasis": 2, "classy": 1, "dyno": 1}

만약 그것이 방법이었다면 그것은 추락했을 것입니다.

;DR에 전화해 . 호출해 보십시오.extravar = lambda o: {k: getattr(o, k, '') for k in o.__dir__() if k[:2] != '__' and type(getattr(o, k, '')).__name__ != 'method'}세 가지 모두에 대해, 하지만 방법이나 마법은 아닙니다.

저는 언급된 다양한 옵션 간의 차이를 보여줄 가치가 있다고 생각합니다. 종종 사진 한 장이 천 마디의 가치가 있습니다.

>>> from pprint import pprint
>>> import inspect
>>>
>>> class a():
    x = 1               # static class member
    def __init__(self):
        self.y = 2      # static instance member
    @property
    def dyn_prop(self): # dynamic property
        print('DYNPROP WAS HERE')
        return 3
    def test(self):     # function member
        pass
    @classmethod
    def myclassmethod(cls): # class method; static methods behave the same
        pass

>>> i = a()
>>> pprint(i.__dict__)
{'y': 2}
>>> pprint(vars(i))
{'y': 2}
>>> pprint(dir(i))
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'dyn_prop',
 'myclassmethod',
 'test',
 'x',
 'y']
>>> pprint(inspect.getmembers(i))
DYNPROP WAS HERE
[('__class__', <class '__main__.a'>),
 ('__delattr__',
  <method-wrapper '__delattr__' of a object at 0x000001CB891BC7F0>),
 ('__dict__', {'y': 2}),
 ('__dir__', <built-in method __dir__ of a object at 0x000001CB891BC7F0>),
 ('__doc__', None),
 ('__eq__', <method-wrapper '__eq__' of a object at 0x000001CB891BC7F0>),
 ('__format__', <built-in method __format__ of a object at 0x000001CB891BC7F0>),
 ('__ge__', <method-wrapper '__ge__' of a object at 0x000001CB891BC7F0>),
 ('__getattribute__',
  <method-wrapper '__getattribute__' of a object at 0x000001CB891BC7F0>),
 ('__gt__', <method-wrapper '__gt__' of a object at 0x000001CB891BC7F0>),
 ('__hash__', <method-wrapper '__hash__' of a object at 0x000001CB891BC7F0>),
 ('__init__',
  <bound method a.__init__ of <__main__.a object at 0x000001CB891BC7F0>>),
 ('__init_subclass__',
  <built-in method __init_subclass__ of type object at 0x000001CB87CA6A70>),
 ('__le__', <method-wrapper '__le__' of a object at 0x000001CB891BC7F0>),
 ('__lt__', <method-wrapper '__lt__' of a object at 0x000001CB891BC7F0>),
 ('__module__', '__main__'),
 ('__ne__', <method-wrapper '__ne__' of a object at 0x000001CB891BC7F0>),
 ('__new__', <built-in method __new__ of type object at 0x00007FFCA630AB50>),
 ('__reduce__', <built-in method __reduce__ of a object at 0x000001CB891BC7F0>),
 ('__reduce_ex__',
  <built-in method __reduce_ex__ of a object at 0x000001CB891BC7F0>),
 ('__repr__', <method-wrapper '__repr__' of a object at 0x000001CB891BC7F0>),
 ('__setattr__',
  <method-wrapper '__setattr__' of a object at 0x000001CB891BC7F0>),
 ('__sizeof__', <built-in method __sizeof__ of a object at 0x000001CB891BC7F0>),
 ('__str__', <method-wrapper '__str__' of a object at 0x000001CB891BC7F0>),
 ('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x000001CB87CA6A70>),
 ('__weakref__', None),
 ('dyn_prop', 3),
 ('myclassmethod', <bound method a.myclassmethod of <class '__main__.a'>>),
 ('test', <bound method a.test of <__main__.a object at 0x000001CB891BC7F0>>),
 ('x', 1),
 ('y', 2)]

요약:

  • vars()그리고.__dict__인스턴스-로컬 속성만 반환합니다.
  • dir()문자열 멤버 이름의 목록으로만 모든 것을 반환합니다. 동적 속성은 호출되지 않습니다.
  • inspect.getmembers() 항목을 튜플 합니다.(name, value)속성을 인 실로동속실선고택사수항락다니합을행하성적제을▁an다를 수락합니다.predicate값으로 멤버를 필터링할 수 있는 인수입니다.

으로 일적으제접방근식은인을 입니다.dir() 및 명행에서, 리고그령getmembers()특정한 성능 고려사항이 적용되지 않는 한 프로그램에서.

더 깨끗하게 유지하기 위해, 나는 포함하지 않았다는 것을 하지 않았습니다.__slots__있는 경우 쿼리할 수 있도록 명시적으로 배치되었으며 직접 사용해야 합니다.저는 또한 약간 털이 날 수 있는 메타 수업을 다루지 않았습니다(대부분의 사람들은 어차피 그것들을 절대 사용하지 않을 것입니다).

언급URL : https://stackoverflow.com/questions/1251692/how-to-enumerate-an-objects-properties-in-python