Intermediate Object-Oriented Programming in Python
Jake Roach
Data Engineer
A special kind of class made up of only abstract methods that create a contract with the classes that implement the interface
$$
$$
Let's start with informal interfaces!
class Course:
def assign_homework(self, assignment_number, due_date):
# Typically, the pass keyword will be used when creating an interface
pass
def grade_assignment(self, assignment_number):
pass
assign_homework()
and grade_assignment()
abstract methodsclass ProgrammingCourse:
def __init__(self, course_name):
self.course_name = course_name
def assign_homework(self, due_date):
# Some implementation of assign_homework here...
def grade_assignment(self, assignment_number):
# Some implementation of grade_assignment here...
from abc import ABC, abstractmethod
class Course(ABC):
@abstractmethod
def assign_homework(self, assignment_number, due_date):
pass
@abstractmethod
def grade_assignment(self, assignment_number):
pass
How are formal interfaces different than abstract base classes?
Interfaces
Abstract base classes
class ProgrammingCourse(Course): def __init__(self, course_name): self.course_name = course_name def assign_homework(self, due_date): # Some implementation of assign_homework here... def grade_assignment(self, assignment_number): # Some implementation of grade_assignment here...
intermediate_oop = ProgrammingCourse("Intermediate Object-Oriented Programming")
class ProgrammingCourse(Course): def __init__(self, course_name): self.course_name = course_name def assign_homework(self, due_date): # Some implementation of assign_homework here...
intermediate_oop = ProgrammingCourse("Intermediate Object-Oriented Programming")
...
intermediate_oop = ProgrammingCourse("Intermediate Object-Oriented Programming")
TypeError: Can't instantiate abstract class ProgrammingCourse with abstract method
grade_assignment
Intermediate Object-Oriented Programming in Python