Difference between __repr__ and __str__ in Python

When implementing a class in Python, you usually implement the __repr__ and __str__ methods.

  1. __str__ should print a readable message
  2. __repr__ should print a message that is unambigous (e.g. name of an identifier, class name, etc).

You can see __str__ as a method for users and __repr__ as a method for developers.

Here is an implementation example for a class that simply stores an attribute (data).

__str__ is called when a user calls the print() function while __repr__ is called when a user just type the name of the instance:

By default when no __str__ or __repr__ methods are defined, the __repr__ returns the name of the class (Length) and __str__ calls __repr__.

Now, let us define the __repr__ method ourself to be more explicit:

we could use it as follows:

When using the print() function in Python, the __str__ is called (if found) and otherwise, __repr__.

so now __repr__ and __str__ have different behaviours:

This entry was posted in Python and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.