Abstraktní základní třídy

Intermediate Object-Oriented Programming in Python

Jake Roach

Data Engineer

Abstraktní základní třídy

Abstraktní základní třídy definují šablonu pro třídy pomocí abstraktních metod, které musí implementovat všechny podtřídy

  • Zajišťují společné chování skupiny tříd
  • Dekorátor @abstractmethod
  • Určeny k dědění, nikoli k přímému vytváření instancí
  • Ne všechny metody musí být abstraktní (konkrétní metody)
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

Vytvoření abstraktní základní třídy

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!")
  • Dědí ze třídy ABC v modulu abc
  • pass
  • Každá třída dědící ze School musí implementovat metodu enroll()
  • Lze také implementovat konkrétní metody
Intermediate Object-Oriented Programming in Python

Implementace abstraktních základních tříd

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 musí definovat metodu enroll()
  • TypeError pokud enroll() není definována
  • HighSchool dědí metodu graduate()
Intermediate Object-Oriented Programming in Python

Více abstraktních metod

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

    @abstractmethod
    def add_course(self, course_name):
        pass

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

  • Dvě abstraktní metody: enroll() a 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

Pojďme si to procvičit!

Intermediate Object-Oriented Programming in Python

Preparing Video For Download...