추상 기본 클래스

Python 중급 객체 지향 프로그래밍

Jake Roach

Data Engineer

추상 기본 클래스

추상 기본 클래스는 모든 자식이 구현해야 하는 추상 메서드를 정의해 클래스의 청사진을 만듭니다.

  • 클래스 그룹의 공통 동작 보장
  • @abstractmethod 데코레이터
  • 인스턴스화하지 않고 상속용
  • 모든 메서드가 추상일 필요는 없음(구현 메서드 가능)
class School:
    # 등록(enroll) 등 수행 
    # 과목 추가(add a course)
class MiddleSchool:
    # 악기 연주, 동아리 가입
    # 단, 등록과 과목 추가는 필수
class HighSchool:
    # 운동부 활동, 대학 지원
    # 단, 등록과 과목 추가는 필수
Python 중급 객체 지향 프로그래밍

추상 기본 클래스 생성

from abc import ABC, abstractmethod

# ABC를 상속하는 추상 기본 클래스 생성 class School(ABC): @abstractmethod def enroll(self): # 이 메서드는 상속받는 클래스에서 # 반드시 구현해야 함 pass
# 구현 메서드는 상속됨 def graduate(self): print("Congrats on graduating!")
  • abc 모듈의 ABC를 상속
  • pass
  • School을 상속하는 클래스는 enroll()을 반드시 구현
  • 구현(콘크리트) 메서드도 포함 가능
Python 중급 객체 지향 프로그래밍

추상 기본 클래스 구현

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

# HighSchool 인스턴스 생성
high_school = HighSchool()
high_school.enroll()
Welcome to high school!
high_school.graduate()
Congrats on graduating!
  • HighSchoolenroll()을 반드시 정의해야 함
  • enroll()이 없으면 TypeError
  • HighSchoolgraduate()를 상속
Python 중급 객체 지향 프로그래밍

여러 추상 메서드

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 = []

    # 추상 메서드 구현
    def enroll(self):
        print("Welcome to high school!")

    # 추상 메서드 구현
    def add_course(self, course_name):
        self.courses.append(course_name)
        print(f"You enrolled in {course_name}")

Python 중급 객체 지향 프로그래밍

Passons à la pratique !

Python 중급 객체 지향 프로그래밍

Preparing Video For Download...