본문 바로가기
공부/Python

Python - 멤버 변수를 출력하는 다양한 방법

by hhhello 2024. 6. 17.

Python에서 클래스의 멤버 변수들을 출력하는 방법들이 있다.

보통 dir함수를 많이 사용한다.

class MyClass:
    def __init__(self):
        self.a = 1

c = MyClass()
print(dir(c))

하지만 출력결과를 보면 참담하다. 내가 만든 a라는 프로퍼티 외에도 다른 것들이 출력되고 있다.

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x']

__dict__라는 것을 사용하면 딕셔너리로 이쁘게 출력된다.

print(c.__dict__)
{'a': 1}

나는 좀 괴짜여서 저런 이쁜 출력은 도저히 못참겠다 하는 사람들은 inspect라는 것을 사용하면 된다.

import inspect

print(inspect.getmembers(c))
[('__class__', <class '__main__.MyClass'>), ('__delattr__', <method-wrapper '__delattr__' of MyClass object at 0x000001BD40FFC390>), ('__dict__', {'a': 1}), ('__dir__', <built-in method __dir__ of MyClass object at 0x000001BD40FFC390>), ('__doc__', None), ('__eq__', <method-wrapper '__eq__' of MyClass object at 0x000001BD40FFC390>), ('__format__', <built-in method __format__ of MyClass object at 0x000001BD40FFC390>), ('__ge__', <method-wrapper '__ge__' of MyClass object at 0x000001BD40FFC390>), ('__getattribute__', <method-wrapper '__getattribute__' of MyClass object at 0x000001BD40FFC390>), ('__getstate__', <built-in method __getstate__ of MyClass object at 0x000001BD40FFC390>), ('__gt__', <method-wrapper '__gt__' of MyClass object at 0x000001BD40FFC390>), ('__hash__', <method-wrapper '__hash__' of MyClass object at 0x000001BD40FFC390>), ('__init__', <bound method MyClass.__init__ of <__main__.MyClass object at 0x000001BD40FFC390>>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x000001BD41210560>), ('__le__', <method-wrapper '__le__' of MyClass object at 0x000001BD40FFC390>), ('__lt__', <method-wrapper '__lt__' of MyClass object at 0x000001BD40FFC390>), ('__module__', '__main__'), ('__ne__', <method-wrapper '__ne__' of MyClass object at 0x000001BD40FFC390>), ('__new__', <built-in method __new__ of type object at 0x00007FF918060E30>), ('__reduce__', <built-in method __reduce__ of MyClass object at 0x000001BD40FFC390>), ('__reduce_ex__', <built-in method __reduce_ex__ of MyClass object at 0x000001BD40FFC390>), ('__repr__', <method-wrapper '__repr__' of MyClass object at 0x000001BD40FFC390>), ('__setattr__', <method-wrapper '__setattr__' of MyClass object at 0x000001BD40FFC390>), ('__sizeof__', <built-in method __sizeof__ of MyClass object at 0x000001BD40FFC390>), ('__str__', <method-wrapper '__str__' of MyClass object at 0x000001BD40FFC390>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x000001BD41210560>), ('__weakref__', None), ('a', 1)]