Look at Python documentation at: http://docs.python.org/reference/datamodel.html#object.repr
object.repr(self)
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). If this is not possible, a
string of the form <...some useful description...> should be returned.
The return value must be a string object. If a class defines
repr() but not str(), then repr() is also used when an
“informal” string representation of instances of that class is
required.
This is typically used for debugging, so it is important that the
representation is information-rich and unambiguous.
object.str(self)
Called by the str() built-in function and by the print statement
to compute the “informal” string representation of an object. This
differs from repr() in that it does not have to be a valid Python
expression: a more convenient or concise representation may be used
instead. The return value must be a string object.
Example:
>>> class A():
... def __repr__(self): return "repr!"
... def __str__(self): return "str!"
...
>>> a = A()
>>> a
repr!
>>> print(a)
str!
>>> class B():
... def __repr__(self): return "repr!"
...
>>> class C():
... def __str__(self): return "str!"
...
>>> b = B()
>>> b
repr!
>>> print(b)
repr!
>>> c = C()
>>> c
<__main__.C object at 0x7f7162efb590>
>>> print(c)
str!
Print function prints the console every arguments __str__
. Like print(str(obj))
.
But in interactive console, it print function's return value's __repr__
. And if __str__
not defined, __repr__
could be used instead.
Ideally, __repr__
means, we should just use that representation to reproduce that object. It shouldn't be identical between different classes, or object's that represents different values, For example, datetime.time:
But __str__
(what we get from str(obj)
) should seem nice, because we show it to user.
>>> a = datetime.time(16, 42, 3)
>>> repr(a)
'datetime.time(16, 42, 3)'
>>> str(a)
'16:42:03' #We dont know what it is could be just print:
>>> print("'16:42:03'")
'16:42:03'
And, sorry for bad English :).
print(repr(None))
givesNone
. How come? – Margarettamargarette