Problem overview
You write an interface and two classes that use it. Printable is an interface with one method, label(), which returns a short text about an item. Two classes implement it:
Book(title, author)has the label<title> by <author>;Ticket(code)has the labelTicket <code>.
Then you write print_all(items), which returns every item's label as a list, in the same order. The items mix books and tickets, and the function may use each only through label().
For Book("Dune", "Herbert") and Ticket("A12") the labels are Dune by Herbert and Ticket A12. The tests print each label on its own line.
Approach
An interface is a promise: any class that implements Printable has a label() method. Code that works with the promise needn't know which class it has. print_all only calls item.label(), so it works for books, tickets and any class added later.
Python has no interface keyword. The usual way is a class that inherits from ABC and has only abstract methods, each marked with @abstractmethod and given the body pass. Then Python refuses to create a Printable directly, or any class that forgets to write label.
Step by step
- Declare the interface's method: in
Printable, put@abstractmethodabovedef label(self)and give it the bodypass. - Book's label: return
self._title, then" by ", thenself._author. There is a space on each side ofby. - Ticket's label: return
"Ticket "followed byself._code, with a space afterTicket. - Start a list in
print_all:labels = []. - Loop over
itemsand appenditem.label()tolabels. The loop doesn't ask whether an item is a book or a ticket. - Return
labels. The labels come out in the order of the items.
The solution in Python
from abc import ABC, abstractmethod
class Printable(ABC):
@abstractmethod
def label(self): pass
class Book(Printable):
def __init__(self, title, author):
self._title = title
self._author = author
def label(self):
return self._title + " by " + self._author
class Ticket(Printable):
def __init__(self, code):
self._code = code
def label(self):
return "Ticket " + self._code
def print_all(items):
labels = []
for item in items:
labels.append(item.label())
return labels
A run with the second example's items, one label per line:
items = [Ticket("B7"), Ticket("C3"), Book("Emma", "Austen")]
print("\n".join(print_all(items)))
Ticket B7
Ticket C3
Emma by Austen
The result of print_all is a list of strings. For [Book("1984", "Orwell")] the label is 1984 by Orwell: a title made of digits is still text, so joining it with + works. An empty list of items gives an empty list.
A third kind of printable
The interface pays off when you add a class. In a file of your own, a badge can join the list without any change to print_all:
class Badge(Printable):
def __init__(self, owner):
self._owner = owner
def label(self):
return "Badge of " + self._owner
print(print_all([Badge("Ann"), Ticket("A1")]))
['Badge of Ann', 'Ticket A1']
print_all was written before Badge existed, and it still works, because Badge keeps the promise of having label(). The function depends on the interface, not on the classes behind it. That is why the lesson says to use each item only through label().
Python details
- Creating the interface or a class that forgot
labelfails:Can't instantiate abstract class Printable without an implementation for abstract method 'label'. That error is how Python enforces the promise. isinstance(Book("a", "b"), Printable)isTrue, so a book counts as a printable thing.- The leading underscore on
_title,_authorand_codemarks them private by convention. Methods of the same class read them freely. print_allreturns the labels; it doesn't print them. A version that printed inside the loop would show the text but returnNone.
Why use an interface at all
Python would let print_all call item.label() on any object that has such a method, even if Printable didn't exist. The interface adds two things. It documents the promise in one place: anyone reading Printable sees what a printable thing must do. And it makes mistakes early: a class that inherits from Printable but forgets label fails the moment you create an object, not later in the middle of print_all with a confusing AttributeError.
The interface has no data and no code. It only names the method. The classes keep their own fields (_title, _author, _code) and decide for themselves how the label is built, so a book and a ticket can be completely different inside and still be handled by one function.
Edge cases and common mistakes
- Missing spaces.
"Ticket"without the trailing space givesTicketA12. The labels are compared as exact text. - Checking the class with
isinstanceinsideprint_all. It works for these two classes but defeats the interface: a third printable class would need a new branch. - Sorting or reordering. The labels must stay in the order of the items.
- Returning
iteminstead ofitem.label(). The list would hold objects, not text. - Forgetting the parentheses on
item.label. That appends a method object instead of its result.
Testing
print_all([Book("a", "b")])returns['a by b']: the smallest book.print_all([Ticket("xxxxxxxxxxxxxxxxxxxx")])returns a list with the one labelTicket xxxxxxxxxxxxxxxxxxxx, with a 20-character code, the longest allowed.print_all([Book("Dune", "Herbert"), Ticket("A12")])returns the labels in the orderDune by Herbert,Ticket A12.- Swapping the two items swaps the labels: the order never changes inside
print_all.
The tests print each returned label on its own line, so a list such as ['Ticket B7', 'Ticket C3'] shows up as two lines.
The same shape of code works for any list of mixed objects: a loop, one method call, one result collected. If you can write it for books and tickets, you can write it for any interface you meet later in a larger program.
