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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.