Overloading str to control print behaviour

Martin McBride, 2019-01-01
Tags print, str
Categories magic methods
In section Python language

As you probably know, you can use the built-in print function to display any object in the Python console window:

print('Hello')       # Hello
print(5 + 1)         # 6
print([0]*3)         # [0, 0, 0]

What happens if we try to print a Person object from our example classes?

person = Person('Mr', 'John', 'Smith')

The result is something like:

<__main__.Person object at 0x000001F8BDAF90F0>

This is rather disappointing, although not surprising since we haven't really told Python what we expect it to do. It is just a default conversion - it tells you what type of object it is, and its memory location, but it isn't particularly pretty or useful.

Making object work with the built-in print function

We need to take a closer look at what the print function does. To print and an object, it first calls that objects __str__ method to convert it to a string. It then displays that string in the console window.

Many built-in objects have a __str__ function that converts its value to a valid string. For object that don't, the default is to create a string based on the object type and its memory address, as we saw above.

If you create your own class, you can control how it is converted to a string by defining a __str__ function.

Implementing __str__ for the Person class

We can extend our Person class to add our own __str__ method:

class Person:

    def __init__(self, title, forename, surname):
        self.title = title
        self.forename = forename
        self.surname = surname

    def __str__(self):
        return(' '.join([self.title, self.forename, self.surname]))

person = Person('Mr', 'John', 'Smith')

In this case the __str__ method simply joins the title, forename and surname, with a space between them. This means that print now has much more sensible behaviour, it outputs:

Mr John Smith

Of course, you can make __str__ do whatever you want.

The new formatting happens without needing to change the way print is called at all. This is why we call them "magic" methods, they appear to add new functionality by magic (really, it isn't magic at all, it is designed into Python itself).

Implementing __str__ is very useful, in fact it is a good idea to do it for any class that you might be using often, as it makes debugging a lot easier.

The str function

Implementing __str__ has another advantage. The- built-in function str also calls __str__. So with our modifiedPerson class we can also do:

s = str(person)

Now s contains the string value 'Mr John Smith'.

Implementing __str__ for the Matrix class

Here is the Matrix class with a __str__ implmentation:

class Matrix:

    def __init__(self, a, b, c, d):
        self.data = [a, b, c, d]

    def __str__(self):
        return '[{}, {}][{}, {}]'.format(self.data[0],

m = Matrix(1, 2, 3, 4)

This will print:

[1, 2][3, 4]

If you found this article useful, you might be interested in the book Functional Programming in Python, or other books, by the same author.


Tag cloud

2d arrays abstract data type alignment and array arrays bezier curve built-in function close closure colour comparison operator comprehension context conversion data types design pattern device space dictionary duck typing efficiency encryption enumerate filter font font style for loop function function composition function plot functools generator gif gradient greyscale higher order function html image processing imagesurface immutable object index inner function input installing iter iterator itertools lambda function len linspace list list comprehension logical operator lru_cache mandelbrot map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path positional parameter print pure function radial gradient range recipes recursion reduce rgb rotation scaling sequence slice slicing sound spirograph str stream string subpath symmetric encryption template text text metrics transform translation transparency tuple unpacking user space vectorisation webserver website while loop zip

Copyright (c) Axlesoft Ltd 2020