eolas/zk/Abstract_base_classes_in_Python.md

1.2 KiB

In TypeScript we can use interfaces to implement classes and use abstract to create abstract methods:

interface Person {
  firstName: string;
  calculateAge(): number;
}

class Programmer implements Person {}
// Must include the property firstName and the method calculateAge
abstract class Person {
  abstract calculateAge(): number;
}

class Child extends Person {}
// Must concretize the abstract calculateAge method from the parent class

The same --or very similar-- functionality can be achieved in Python by importing the abc module ("Abstract Base Class").

from abc import ABC, abstractmethod

class Person(ABC):
    @abstractmethod
    def calculate_age(self):
        pass


class Child(Person):
    def calculate_age(self):
        # Must concretize the abstract method in Person

Only use @abstractmethod if the method must exist on the child and must be defined in the child (not the parent). If you just want to redefine a parent method, you can use normal inheritance. Python will interpret the methods upwards from the child, before getting to the parent.