Overloading str to control print behaviour


Martin McBride, 2019-01-01
Tags print str
Categories magic methods

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')
print(person)

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')
print(person)

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],
                                         self.data[1],
                                         self.data[2],
                                         self.data[3])

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

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.

Prev

Popular tags

2d arrays abstract data type alignment and animation arc array arrays behavioural pattern bezier curve built-in function callable object chain circle classes close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data types design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop function function composition function plot functools game development generativepy tutorial generator geometry gif gradient greyscale higher order function hsl html image image processing imagesurface immutable object index inner function input installing iter iterable iterator itertools l system lambda function len line linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path pattern permutations polygon positional parameter print pure function python standard library radial gradient range recipes rectangle recursion reduce repeat rgb rotation scaling sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency triangle tuple turtle unpacking user space vectorisation webserver website while loop zip