Start learning free

LESSON 644 OF 673 · OBJECT-ORIENTED PROGRAMMING

Printable Things in Python: Interfaces with ABC

Practice Read the full explanation

You write an interface and two classes that use it.

Printable is an interface with one method, label(). It returns a short text about the item.

Two classes implement it:

  • Book(title, author). Its label is the title, then by, then the author.
  • Ticket(code). Its label is Ticket, then the code.

One space separates the words of a label.

In Python, an interface is a class that inherits from ABC. Its method gets @abstractmethod and the body pass.

Then write print_all(items). It returns every item's label, in the same order.

The items mix books and tickets. Use each one only through label().

The starter code already has the classes and their constructors. The harness prints each label on its own line.

 

Example 1:

Input: Book("Dune", "Herbert"), Ticket("A12")
Output:
Dune by Herbert
Ticket A12

Explanation: The book joins its title and author with by.
The ticket puts Ticket before its code.

Example 2:

Input: Ticket("B7"), Ticket("C3"), Book("Emma", "Austen")
Output:
Ticket B7
Ticket C3
Emma by Austen

Explanation: The labels keep the order of the items.

Example 3:

Input: Book("1984", "Orwell")
Output:
1984 by Orwell

Explanation: A title can be digits. It is still text.

 

Constraints:

  • 1 to 100 items.
  • Each title, author and code is one word.
  • A word has 1 to 20 letters or digits.
STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · OBJECT-ORIENTED PROGRAMMING

    Printable Things in Python, explained

    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 label Ticket <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

    1. Declare the interface's method: in Printable, put @abstractmethod above def label(self) and give it the body pass.
    2. Book's label: return self._title, then " by ", then self._author. There is a space on each side of by.
    3. Ticket's label: return "Ticket " followed by self._code, with a space after Ticket.
    4. Start a list in print_all: labels = [].
    5. Loop over items and append item.label() to labels. The loop doesn't ask whether an item is a book or a ticket.
    6. 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 label fails: 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) is True, so a book counts as a printable thing.
    • The leading underscore on _title, _author and _code marks them private by convention. Methods of the same class read them freely.
    • print_all returns the labels; it doesn't print them. A version that printed inside the loop would show the text but return None.

    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 gives TicketA12. The labels are compared as exact text.
    • Checking the class with isinstance inside print_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 item instead of item.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 label Ticket xxxxxxxxxxxxxxxxxxxx, with a 20-character code, the longest allowed.
    • print_all([Book("Dune", "Herbert"), Ticket("A12")]) returns the labels in the order Dune 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.

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free