Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. >>> from collections import namedtuple
  2. >>> A = namedtuple("A", ["foo"])
  3. >>> print(A(foo=1))
  4. A(foo=1)
  5. >>> str(A(foo=1))
  6. 'A(foo=1)'
  7. >>> repr(A(foo=1))
  8. 'A(foo=1)'
  9.  
  10. def __repr__(self):
  11. return 'className(attrA={attrA}, attrB={attrB})'.format(**vars(self)))
  12.  
  13. from collections import namedtuple
  14.  
  15. def nice_repr(obj):
  16. def nice_repr(self):
  17. return repr(
  18. namedtuple(
  19. type(self).__name__,
  20. vars(self)
  21. )(**vars(self))
  22. )
  23.  
  24. obj.__repr__ = nice_repr
  25.  
  26. return obj
  27.  
  28. @nice_repr
  29. class A:
  30. def __init__(self, b, c):
  31. self.b = b
  32. self.c = c
  33.  
  34. print(repr(A(1, 2))) # Outputs: A(c=2, b=1)
  35.  
  36. def nice_repr(obj):
  37. """ Decorator to bring namedtuple's __repr__ behavior to regular classes. """
  38.  
  39. def nice_repr(self):
  40. v = vars(self)
  41.  
  42. # Prevent infinite looping if `vars` happens to include `self`.
  43. del(v['self'])
  44.  
  45. return repr(namedtuple(type(self).__name__, v)(**v))
  46.  
  47. obj.__repr__ = nice_repr
  48.  
  49. return obj
  50.  
  51. class BaseClass:
  52.  
  53. # logic can be used with in `__repr__` itself.
  54. # creating separate function to make it more clear
  55. def _get_formatted_string(self):
  56. return '{class_name}({params})'.format(
  57. class_name=self.__class__.__name__,
  58. params=', '.join('{}={}'.format(k, v) for k, v in vars(self).items()))
  59.  
  60. def __repr__(self):
  61. return self._get_formatted_string()
  62.  
  63. class child(BaseClass):
  64.  
  65. def __init__(self, a, b):
  66. self.a = a
  67. self.b = b
  68.  
  69. >>> c = child(1, 2)
  70. >>> repr(c)
  71. 'child(a=1, b=2)'
  72. >>> str(c)
  73. 'child(a=1, b=2)'
  74.  
  75. class Foo:
  76. def __init__(self):
  77. self.a="value"
  78.  
  79. def __str__(self):
  80. return "a is: "+self.a
  81.  
  82. variable=Foo()
  83. print variable
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement