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?
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?
When we create new types by defining classes, we can take advantage of certain features of Python to make the new classes convenient to use. One of these features is "special methods", also referred to as "magic methods".
Special methods have names that begin and end with two underscores. We define them, but do not usually call them directly by name. Instead, they execute automatically under under specific circumstances.
It is convenient to be able to output the value of an instance of an object by using a print statement. When we do this, we would like the value to be represented in the output in some understandable unambiguous format. The repr special method can be used to arrange for this to happen. If we define this method, it can get called automatically when we print the value of an instance of a class for which we defined this method. It should be mentioned, though, that there is also a str special method, used for a similar, but not identical purpose, that may get precedence, if we have also defined it.
If we have not defined, the repr method for the Point3D class, and have instantiated my_point as an instance of Point3D, and then we do this ...
print my_point ... we may see this as the output ...
Not very nice, eh?
So, we define the repr or str special method, or both, to get better output.
Output ...
(1, 2, 3) (1, 2, 3)
Implement repr for every class you implement. There should be no excuse. Implement str for classes which you think readability is more important of non-ambiguity.
Refer this link: https://www.pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/
__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:
This is explained quite well in the Python documentation:
So what you're seeing here is the default implementation of __repr__, which is useful for serialization and debugging.
__repr__
is used by the standalone Python interpreter to display a class in printable format. Example:In cases where a
__str__
method is not defined in the class, it will call the__repr__
function in an attempt to create a printable representation.Additionally,
print()
ing the class will call__str__
by default.Documentation, if you please
The __repr__ method simply tells Python how to print objects of a class