Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- >>> from collections import namedtuple
- >>> A = namedtuple("A", ["foo"])
- >>> print(A(foo=1))
- A(foo=1)
- >>> str(A(foo=1))
- 'A(foo=1)'
- >>> repr(A(foo=1))
- 'A(foo=1)'
- def __repr__(self):
- return 'className(attrA={attrA}, attrB={attrB})'.format(**vars(self)))
- from collections import namedtuple
- def nice_repr(obj):
- def nice_repr(self):
- return repr(
- namedtuple(
- type(self).__name__,
- vars(self)
- )(**vars(self))
- )
- obj.__repr__ = nice_repr
- return obj
- @nice_repr
- class A:
- def __init__(self, b, c):
- self.b = b
- self.c = c
- print(repr(A(1, 2))) # Outputs: A(c=2, b=1)
- def nice_repr(obj):
- """ Decorator to bring namedtuple's __repr__ behavior to regular classes. """
- def nice_repr(self):
- v = vars(self)
- # Prevent infinite looping if `vars` happens to include `self`.
- del(v['self'])
- return repr(namedtuple(type(self).__name__, v)(**v))
- obj.__repr__ = nice_repr
- return obj
- class BaseClass:
- # logic can be used with in `__repr__` itself.
- # creating separate function to make it more clear
- def _get_formatted_string(self):
- return '{class_name}({params})'.format(
- class_name=self.__class__.__name__,
- params=', '.join('{}={}'.format(k, v) for k, v in vars(self).items()))
- def __repr__(self):
- return self._get_formatted_string()
- class child(BaseClass):
- def __init__(self, a, b):
- self.a = a
- self.b = b
- >>> c = child(1, 2)
- >>> repr(c)
- 'child(a=1, b=2)'
- >>> str(c)
- 'child(a=1, b=2)'
- class Foo:
- def __init__(self):
- self.a="value"
- def __str__(self):
- return "a is: "+self.a
- variable=Foo()
- print variable
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement