Объектно-ориентированное программирование на Python: средний уровень
Jake Roach
Data Engineer
Абстрактные базовые классы создают шаблон для классов, определяя абстрактные методы, которые должны быть реализованы во всех дочерних классах
@abstractmethodclass 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
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!")
ABC из модуля abcpassSchool, должен реализовать метод enroll()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 обязан определить метод enroll()TypeError, если метод enroll() не определёнHighSchool наследует метод graduate()class School(ABC):
@abstractmethod
def enroll(self):
pass
@abstractmethod
def add_course(self, course_name):
pass
def graduate(self):
print("Congrats on graduating!")
enroll() и 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}")
Объектно-ориентированное программирование на Python: средний уровень