Sunday, 29 March 2015

Difference between __str__ and __repr__ in python

Here is what the doc says
Called by the repr() built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).
Called by the str() built-in function and by the print statement to compute the "informal" string representation of an object.

 Now lets take an example,

>>> from decimal import Decimal
>>> a = Decimal(1.25)
>>> print(a)
1.25                  <---- span=""> this is from __str__
>>> a
Decimal('1.25')       <---- span=""> this is from __repr__
The __str__ is intended to be as human-readable as possible, whereas the __repr__ should aim to be something that could be used to recreate the object, although it often won't be exactly how it was created, as in this case.
It's also not unusual for both __str__ and __repr__ to return the same value (certainly for built-in types).


Post a Comment