Advanced OOP and patterns · 2 / 15 Theory

Abstract classes and contracts

An abstract class defines *what* its subclasses must be able to do without saying *how*. It is created by inheriting from abc.ABC and marking the mandatory methods with @abstractmethod. It cannot be instantiated, and neither can a subclass that does not implement all the abstract methods.

from abc import ABC, abstractmethod

class Notifier(ABC):
    @abstractmethod
    def send(self, message):
        """Each subclass decides how it is sent."""

    def notice(self, message):              # concrete method that uses the abstract one
        return self.send("NOTICE: " + message)

class Email(Notifier):
    def send(self, message):
        return f"email -> {message}"

class Sms(Notifier):
    def send(self, message):
        return f"sms -> {message}"

class Incomplete(Notifier):
    pass                                    # does not implement send

for n in (Email(), Sms()):
    print(n.notice("hello"))      # email -> NOTICE: hello   /   sms -> NOTICE: hello

try:
    Notifier()
except TypeError:
    print("abstract class")    # abstract class

try:
    Incomplete()
except TypeError:
    print("send is missing")       # send is missing
  • The abstract class can also have concrete methods that use the abstract ones (the common skeleton).
  • The code using the shapes only depends on the contract (send), not on the concrete class: that is polymorphism.
  • Python also supports *duck typing*: if an object has the required methods, it works, even if it inherits from nothing. Abstract classes are useful when you want the error to show up when creating the object, not when using it.
  • For contracts without inheritance there is typing.Protocol, which describes the shape an object must have and is checked by type tools.

You practice it in Shapes with an abstract class.