if you apply str or repr to an object, Python is looking for a corresponding method _ str _ or _ repr _ in the class definition of the object. If the method does exist, it will be called.
In the following example, we define a class A, having neither a _ str _ nor a _ repr _ method. We want to see, what happens, if we use print directly on an instance of this class, or if we apply str or repr to this instance:
>>> class A:
... pass
...
>>> a = A()
>>> print(a)
<__main__.A object at 0xb720a64c>
>>> print(repr(a))
<__main__.A object at 0xb720a64c>
>>> print(str(a))
<__main__.A object at 0xb720a64c>
>>> a
<__main__.A object at 0xb720a64c>
>>>
As both methods are not available, Python uses the default output for our object "a".
If a class has a _ str _ method, the method will be used for an instance x of that class, if either the function str is applied to it or if it is used in a print function. _ str _ will not be used, if repr is called, or if we try to output the value directly in an interactive Python shell:
>>> class A:
... def __str__(self):
... return "42"
...
>>> a = A()
>>> print(repr(a))
<__main__.A object at 0xb720a4cc>
>>> print(str(a))
42
>>> a
<__main__.A object at 0xb720a4cc>
Otherwise, if a class has only the _ repr _ method and no _ str _ method, _ repr _ will be applied in the situations, where _ str _would be applied, if it were available:
>>> class A:
... def __repr__(self):
... return "42"
...
>>> a = A()
>>> print(repr(a))
42
>>> print(str(a))
42
>>> a # notice the difference with the example above
42
A frequently asked question is when to use _ repr _ and when _ str _.
_ str _ is always the right choice, if the output should be for the end user or in other words, if it should be nicely printed.
_ repr _ on the other hand is used for the internal representation of an object. The output of _ repr _ should be - if feasible - a string which can be parsed by the python interpreter. The result of this parsing is in an equal object.
This means that the following should be true for an object "o":
o == eval(repr(o))
This is shown in the following interactive Python session:
>>> l = [3,8,9]
>>> s = repr(l)
>>> s
'[3, 8, 9]'
>>> l == eval(s)
True
>>> l == eval(str(l))
True
>>>
We can see that eval(repr_s) returns again a datetime.datetime object. The String created by str can't be turned into a datetime.datetime object by parsing it.
We will extend our robot class with a repr method. We dropped the other methods to keep this example simple:
class Robot:
def __init__(self, name, build_year):
self.name = name
self.build_year = build_year
def __repr__(self):
return "Robot('" + self.name + "', " + str(self.build_year) + ")"
if __name__ == "__main__":
x = Robot("Marvin", 1979)
x_str = str(x)
print(x_str)
print("Type of x_str: ", type(x_str))
new = eval(x_str)
print(new)
print("Type of new:", type(new))
x_str has the value Robot('Marvin', 1979). eval(x_str) converts it again into a Robot instance.
The script returns the following output:
Robot("Marvin",1979)
Type of x_str: <class 'str'>
Robot("Marvin",1979)
Type of new: <class '__main__.Robot'>
Now it's time to extend our class with a user friendly str method:
class Robot:
def __init__(self, name, build_year):
self.name = name
self.build_year = build_year
def __repr__(self):
return "Robot('" + self.name + "', " + str(self.build_year) + ")"
def __str__(self):
return "Name: " + self.name + ", Build Year: " + str(self.build_year)
if __name__ == "__main__":
x = Robot("Marvin", 1979)
x_str = str(x)
print(x_str)
print("Type of x_str: ", type(x_str))
new = eval(x_str)
print(new)
print("Type of new:", type(new))
When we start this program, we can see that it is not possible to convert our string x_str, created via str(x), into a Robot object anymore.
Name: Marvin, Build Year: 1979
Type of x_str: <class 'str'>
Traceback (most recent call last):
File "robot_class6.py", line 19, in <module>
new = eval(x_str)
File "<string>", line 1
Name: Marvin, Build Year: 1979
^
SyntaxError: invalid syntax