Abstract Base Classes

Explore the concept of abstract base classes.

What are abstract base classes?

An abstract base class provides a blueprint for other classes that derive from it by defining interfaces that they must implement. In the lesson on OOP, we saw an example of inheritance. Let’s revisit that example.

Press + to interact
class Dataset:
"""Parent class."""
def __init__(self, path: str) -> None:
print("Initializing parent Dataset...")
self.path = path
def load(self) -> None:
print(f"Loading {self.path}...")
# load data...
def clean(self) -> None:
raise NotImplementedError
def save(self, path: str) -> None:
print(f"Saving {path}...")
# save data...
class FooDataset(Dataset):
"""Child class."""
def __init__(self, path: str) -> None:
super().__init__(path)
print("Initializing child FooDataset...")
def clean(self) -> None:
print("Cleaning foo...")
# clean data...
class BarDataset(Dataset):
"""Child class."""
def __init__(self, path: str) -> None:
super().__init__(path)
print("Initializing chid BarDataset...")
def clean(self) -> None:
print("Cleaning bar...")
if __name__ == "__main__":
foo_dataset = FooDataset("/foo")
bar_dataset = BarDataset("/bar")
foo_dataset.load()
foo_dataset.clean()
foo_dataset.save("/foo.clean")
bar_dataset.load()
bar_dataset.clean()
bar_dataset.save("/bar.clean")

Click the “Run” button in the widget to see the code in action.

We notice that Dataset is the parent class, and FooDataset and BarDataset are the child classes. We also notice that the parent class implements two methods, load and save, which are not overridden in the child class. The method clean isn’t implemented in the parent class, but it is implemented in the child classes. If the clean method of the parent class is invoked, it raises the NotImplementedError exception.

Do we ever need to instantiate an object of type Dataset? No, because in ...