Imagine you’ve been hired to help write a program to keep track of books in a bookstore. Every record about a book would probably include the title, authors, publisher, price, and ISBN, which stands for International Standard Book Number, a unique identifier for a book.
Read this code and try to guess what it prints:
| | python_book = Book( |
| | 'Practical Programming', |
| | ['Campbell', 'Gries', 'Montojo'], |
| | 'Pragmatic Bookshelf', |
| | '978-1-6805026-8-8', |
| | 25.0) |
| | |
| | survival_book = Book( |
| | "New Programmer's Survival Manual", |
| | ['Carter'], |
| | 'Pragmatic Bookshelf', |
| | '978-1-93435-681-4', |
| | 19.0) |
| | |
| | print('{0} was written by {1} authors and costs ${2}'.format( |
| | python_book.title, python_book.num_authors(), python_book.price)) |
| | |
| | print('{0} was written by {1} authors and costs ${2}'.format( |
| | survival_book.title, survival_book.num_authors(), survival_book.price)) |
You might guess that this code creates two book objects, one called Practical Programming and one called New Programmer’s Survival Manual. You might even guess the output:
| | Practical Programming was written by 3 authors and costs $25.0 |
| | New Programmer's Survival Manual was written by 1 authors and costs $19.0 |
There’s a problem, though: this code doesn’t run. Python doesn’t have a Book type. And that is what this chapter is about: how to define and use your own types.