Python __repr__ Method – Purpose and Usage of __repr__ Method in Python

python

def __repr__(self):
  return '<%s %s (%s:%s) %s>' % (
    self.__class__.__name__, self.urlconf_name, self.app_name,
    self.namespace, self.regex.pattern)

What is the significance/purpose of this method?

Best Answer

__repr__ should return a printable representation of the object, most likely one of the ways possible to create this object. See official documentation here. __repr__ is more for developers while __str__ is for end users.

A simple example:

>>> class Point:
...     def __init__(self, x, y):
...             self.x, self.y = x, y
...     def __repr__(self):
...             cls = self.__class__.__name__
...             return f'{cls}(x={self.x!r}, y={self.y!r})'
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
Related Question