Python – Difference between __str__ and __repr__

__repr__  and __str__  dunders are quite similar in Python.

If you need  a quick summary of these 2, then these 3 points will be enough:

  • __repr__ dunder presents the class object, whenever it is called by the terminal
  • __str__ dunder presents the object, when it is printed
  • If a __str__ dunder does not exist in the class object, and it is printed, then the __repr__ is taken. Thus, if you only have time to write one, write the __repr__  one.

The code, used for the FootballPlayer()  class is this one:

class FootballPlayer:
    def __init__(self, name, number):
        self.name = name
        self.number = number

    def __str__(self):
        return f'Football player named {self.name} with number {self.number} on the jersey.'

    def __repr__(self):
        return f'My name is {self.name}, pleased to meet you!'

Enjoy!