Plugging into Python Syntax: More Special Methods

In What Are Those Underscores?, you learned that some Python syntax, such as + or ==, triggers method calls. For example, when Python sees ’abc’ + ’123’, it turns that into ’abc’.__add__(’123’). When we call print(obj), then obj.__str__() is called to find out what string to print.

You can do this too. All you need to do is define these special methods inside your classes.

The output Python produces when we print a Book isn’t particularly useful:

 >>>​​ ​​python_book​​ ​​=​​ ​​Book(
 ...​​ ​​'Practical Programming'​​,
 ...​​ ​​[​​'Campbell'​​,​​ ​​'Gries'​​,​​ ​​'Montojo'​​],
 ...​​ ​​'Pragmatic Bookshelf'​​,
 ...​​ ​​'978-1-93778-545-1'​​,
 ...​​ ​​25.0)
 >>>​​ ​​print(python_book) ...

Get Practical Programming, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.