Search

멤버변수 출력하기

클래스 내에서 정의된 변수를 멤버변수라고한다 ( self.name )
이를 확인하고 싶을 때 쓰는 몇가지 방법을 정리해보겠다
class Student: def __init__(self, name, age): self.name = name self.age = age
Python
복사

1. dir 함수

student1 = Student('James', 10) print(dir(student1)) # ['__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__', 'age', 'name']
Python
복사

2. __ dict __

dir과 다른 점은 init 부분에서 생성된 멤버변수만 출력된다는 것이다
print(student1.__dict__) # {'name': 'James', 'age': 10}
Python
복사

3. inspect

더 자세하게 뽑아낼 수 있다.
import inspect print(inspect.getmembers(student1)) #[('__class__', <class '__main__.Student'>), ('__delattr__', <method-wrapper '__delattr__' of Student object at 0x7f514a8b81d0>), #('__dict__', {'name': 'James', 'age': 10}), ('__dir__', <built-in method __dir__ of Student object at 0x7f514a8b81d0>), #('__doc__', None), ('__eq__', <method-wrapper '__eq__' of Student object at 0x7f514a8b81d0>), ('__format__', <built-in method __format__ of Student object at 0x7f514a8b81d0>), #('__ge__', <method-wrapper '__ge__' of Student object at 0x7f514a8b81d0>), ('__getattribute__', <method-wrapper '__getattribute__' of Student object at 0x7f514a8b81d0>), #('__gt__', <method-wrapper '__gt__' of Student object at 0x7f514a8b81d0>), ('__hash__', <method-wrapper '__hash__' of Student object at 0x7f514a8b81d0>), #('__init__', <bound method Student.__init__ of <__main__.Student object at 0x7f514a8b81d0>>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x559b698>), ('__le__', <method-wrapper '__le__' of Student object at 0x7f514a8b81d0>), ('__lt__', <method-wrapper '__lt__' of Student object at 0x7f514a8b81d0>), ('__module__', '__main__'), ('__ne__', <method-wrapper '__ne__' of Student object at 0x7f514a8b81d0>), ('__new__', <built-in method __new__ of type object at 0x9d17a0>), ('__reduce__', <built-in method __reduce__ of Student object at 0x7f514a8b81d0>), ('__reduce_ex__', <built-in method __reduce_ex__ of Student object at 0x7f514a8b81d0>), ('__repr__', <method-wrapper '__repr__' of Student object at 0x7f514a8b81d0>), ('__setattr__', <method-wrapper '__setattr__' of Student object at 0x7f514a8b81d0>), ('__sizeof__', <built-in method __sizeof__ of Student object at 0x7f514a8b81d0>), ('__str__', <method-wrapper '__str__' of Student object at 0x7f514a8b81d0>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x559b698>), ('__weakref__', None), ('age', 10), ('name', 'James')]
Python
복사