Книга: Practical Programming, Fourth Edition
Назад: Exercises
Дальше: Understanding a Problem Domain

Chapter 14
Object-Oriented Programming

Imagine you’ve been hired to help write a program to keep track of books in a bookstore. Every record about a book would likely 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​(f​'{python_book.title} was written by {python_book.num_authors()} '
 'authors and costs ${python_book.price}'​)
 
 print​(f​'{survival_book.title} was written by {survival_book.num_authors()} '
 'authors and costs ${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.

Назад: Exercises
Дальше: Understanding a Problem Domain