Python informer

Improve your Python coding skills

print

As you probably know, you can use the builtin 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 builtin 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 builtin 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]