__repr__()함수를 만들어서 나열식으로 만들면 되긴 하지만 맴버 변수가 몇십개가 되면 노가다가 아닐 수 없다.
그래서 자동으로 이런 기능을 하는 클래스를 만들어서 상속을 받으면 될 것 같아 구현해 보았다.
아래와 같이 test.py를 작성한 후 실행해 보자.
class Representer:
def __repr__(self):
attributes = []
for key in dir(self):
if not key.startswith('_'):
try:
value = getattr(self, key)
except (AttributeError, ValueError):
pass
if isinstance(value, str):
attributes.append("'{0}': '{1}'".format(key, value))
elif isinstance(value, int) or isinstance(value, float):
attributes.append("'{0}': {1}".format(key, value))
return '{' + ', '.join(attributes) + '}'
class A:
name = 'nahaha'
number = 19
class B(A, Representer):
_secret = 'secret'
pi = 3.141592
email = 'truwater@gmail.com'
b = B()
print b
$ python test.py
{'email': 'truwater@gmail.com', 'name': 'nahaha', 'number': 19, 'pi': 3.141592}
파이썬에 중독된 지금은 C++로는 코딩 못할 것 같다. ^^;
파이썬 만세~
댓글 없음:
댓글 쓰기