Writing a Method in Class Book

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) -> ...

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.