String Description For A Custom Python Object

This post presents a custom Python class Computer overriding the default class string representation. Example:

laptop = Computer("laptop", "5GHz")

# laptop computer, 5GHz processor

Override __str__

The goal of __str__ is to provide a human-readable printed representation of the object. In many cases, for example logging or printing a custom Python object, __str__ is called to determine the string used for the object.

When using print, __str__ will be called to determine the string that should be printed.

class Computer:
    def __init__(self, form_factor, processor_speed):
        self._form_factor = form_factor
        self._processor_speed = processor_speed

    def __str__(self):
        return f'{self._form_factor} computer, ' + \
               f'{self._processor_speed} processor'

Override __repr__

The goal of __repr__ is to provide an unambiguous representation of a custom Python object. Additionally, __repr__ should return an expression that could be used to recreate the object.

Overriding __repr__ is not necessary to print a custom string for a custom object. Instead, override __str__.

class Computer:
    # ...

   def __repr__(self):
       class_name = self.__class__.__name__
       return f'{class_name}(' + \
              f'{repr(self._form_factor)}, ' + \

    # ...

Custom String Conversion

That’s it! By overriding __str__ and __repr__ you can convert an object to a custom string representation for custom classes implemented in Python.

laptop = Computer('laptop', '5GHz')

# laptop computer, 5GHz processor

# Computer('laptop', '5GHz')