4.13. Abstract Classes

4.13.1. What it is?

  • Cannot instantiate

  • Possible to indicate which method must be implemented by child

  • Inheriting class must implement all methods

  • Some methods can have implementation

4.13.2. When use it?

4.13.3. Abstract classes and methods

Listing 4.54. Abstract Class
from abc import ABC, abstractmethod

class Document(ABC):
    def __init__(self, filename):
        self.filename = filename

    def open(self):
        with open(self.filename) as file:
            return file.read()

    def display(self):

class PDFDocument(Document):
    def display(self):
        content = super().display()
        # display ``content`` as PDF Document

class WordDocument(Document):
    def display(self):
        content = self.display()
        # display ``content`` as Word Document

file1 = PDFDocument('filename.pdf')

file2 = Document('filename.txt')  # TypeError: Can't instantiate abstract class Document with abstract methods display