What is the difference between __str__ and __repr__?

__str__ and __repr__ are two special methods in Python classes. The __str__ method is called when you call str() on an object, and is used to return a string representation of the object. The __repr__ method is called when you call repr() on an object, and is used to return a representation of the object that is more "formal" and can be used to recreate an object.

Watch a course Python - The Practical Guide

The main difference between __str__ and __repr__ is that __str__ should return a string that is easy for humans to read, while __repr__ should return a string that is more machine-readable and is intended to be used for debugging. For example, __repr__ might return something like 'Person(name='Alice', age=30)', which could be used to recreate an object, while __str__ might return something like 'Alice (age 30)', which is easier for humans to read.

In general, it is a good idea to define both __str__ and __repr__ for your objects, and to make sure that the __repr__ method is a more "formal" representation of the object that can be used to recreate it, while the __str__ method is a more human-readable representation of the object.