Abstract Base Classes

Intermediate Object-Oriented Programming in Python

Jake Roach

Data Engineer

Abstract base classes

Abstract base classes create a blueprint for classes by defining abstract methods that must be implemented by all children

  • Ensures common behavior for a group of classes
  • @abstractmethod decorator
  • Meant to be inherited, not instantiated
  • Not all methods in abstract base class must be abstract (concrete methods)
class School:
    # Do things such as enroll 
    # and add a course
class MiddleSchool:
    # Play an instrument, join a club
    # but must enroll and add courses
class HighSchool:
    # Play a varsity sport, apply
    # for college, but must enroll 
    # and add courses
Intermediate Object-Oriented Programming in Python

Creating an abstract base class

from abc import ABC, abstractmethod

# Create an abstract base class that inherits # from ABC class School(ABC): @abstractmethod def enroll(self): # This method must be implemented # in classes that inherit from it pass
# Concrete methods are inherited def graduate(self): print("Congrats on graduating!")
  • Inherit from the ABC class in the abc module
  • pass
  • Any class that inherits School must implement the enroll() method
  • Can also implement concrete methods
Intermediate Object-Oriented Programming in Python

Implementing abstract base classes

class HighSchool(School):
    def enroll(self):
        print("Welcome to high school!")

# Create an instance of HighSchool
high_school = HighSchool()
high_school.enroll()
Welcome to high school!
high_school.graduate()
Congrats on graduating!
  • HighSchool must define an enroll() method
  • TypeError if enroll() is not defined
  • HighSchool inherits the graduate() method
Intermediate Object-Oriented Programming in Python

Multiple abstract methods

class School(ABC):
    @abstractmethod
    def enroll(self):
        pass

    @abstractmethod
    def add_course(self, course_name):
        pass

    def graduate(self):
        print("Congrats on graduating!")

  • Two abstract methods, enroll() and add_course()
class HighSchool(School):
    def __init__(self):
        self.courses = []

    # Implementing abstract method
    def enroll(self):
        print("Welcome to high school!")

    # Implementing abstract method
    def add_course(self, course_name):
        self.courses.append(course_name)
        print(f"You enrolled in {course_name}")

Intermediate Object-Oriented Programming in Python

Let's practice!

Intermediate Object-Oriented Programming in Python

Preparing Video For Download...