Advertisement
Guest User

Untitled

a guest
Mar 31st, 2015
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.65 KB | None | 0 0
  1. def slots_repr(self):
  2. """
  3. Provides a readable, namedtuple-like __repr__ for classes that use __slots__.
  4.  
  5. Usage:
  6.  
  7. >>> class A(object):
  8. ... __slots__ = ['b']
  9. ... __repr__ = slots_repr
  10. ...
  11. >>> a = A()
  12. >>> a.b = 5
  13. >>> repr(a)
  14. "A(b=5)"
  15. """
  16.  
  17. return "{class_name}({formatted_slots})".format(
  18. class_name=self.__class__.__name__,
  19. formatted_slots=', '.join(
  20. "{slot}={value}".format(
  21. slot=slot,
  22. value=repr(getattr(self, slot))
  23. )
  24. for slot in self.__class__.__slots__
  25. if getattr(self, slot, None) is not None
  26. )
  27. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement