Overloading str to control print behaviour

By 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]

See also

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

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

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