September 2013
Intermediate to advanced
350 pages
9h 38m
English
As you saw in Chapter 7, Using Methods, there are two ways to call a method. One way is to access the method through the class, and the other is to use object-oriented syntax. These two calls are equivalent:
| | >>> str.capitalize('browning') |
| | 'Browning' |
| | >>> 'browning'.capitalize() |
| | 'Browning' |
We’d like to be able to write similar code involving class Book. For example, we might want to be able to ask how many authors a Book has:
| | >>> Book.num_authors(ruby_book) |
| | 3 |
| | >>> ruby_book.num_authors() |
| | 3 |
To get this to work, we’ll define a method called num_authors inside Book. Here it is:
| | class Book: |
| | """Information about a book.""" |
| | |
| | def num_authors(self): |
| | """ (Book) -> ... |
Read now
Unlock full access