zjm1126 zjm1126 - 1 year ago 74
Python Question

Purpose of Python's __repr__

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?

Answer Source

__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):
...     return 'Point(x=%s, y=%s)' % (self.x, self.y)
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download