September 2013
Intermediate to advanced
350 pages
9h 38m
English
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) ... |
Read now
Unlock full access