What is the difference between __str__ and __repr__?
In this article you will learn the difference between __str__ and __repr__ in Python – find out in which situation you use each operator!
What’s up programmer, ok? Let’s learn more about Python’s __str__ and __repr__ statements!
Basically __str__ serves to display an object to the end user
__repr__ is used to display an object to code developers
Check out this example:
import datetime today = datetime.datetime.now() print(str(today)) # 2020-07-08 13:16:04.162076 print(repr(today)) # datetime.datetime(2020, 7, 8, 13, 16, 4, 162076)
As you can see the outputs are different, each one matters in a specific way to the reader.
The first one, with str, is readable by the clients, while the one with repr is not
But most classes have no differentiation in the final result, so be careful
See an example:
class Person: def __init__(self, name, age): self.name = name self.age = age joao = Person("João", 30) print(str(joao)) # <__main__.Pessoa object at 0x7f7c8903d4c0> print(repr(joao)) # <__main__.Pessoa object at 0x7f7c8903d4c0>
In this case it would have no effect to show the str to the end client
We can assume that the __str__ function will provide the most human-readable form of an object possible.
__repr__ is commonly used by developers to debug the application, where they can receive more information about an object at the prompt.
In this article we learned the difference between __str__ and __repr__
The str function serves to display the results of a class to end clients
With repr, we can get other data from a class, which are not useful to users of the system.
Do you want to learn more about Python? Click here!