Juhans

추상클래스(Abstract Class) 란?

  • 추상클래스는 미구현 추상메서드를 한 개 이상 가지며, 자식클래스에서 해당 추상 메서드를 반드시 구현하도록 강제한다.
  • 추상클래스에서 추상메서드를 생략하면 객체를 생성하더라도 에러가 발생하지는 않는다.
  • 추상클래스에서 미구현 추상메서드가 존재하고 자식클래스에서 이를 구현하지 않았다면 import할 때 까지는 에러가 발생하지 않으나 객체를 생성하면 에러가 발생한다. (자식클래스, 추상클래스 모두 에러)
  • 반드시 "abc" 모듈을 import해야한다.
  • 추상클래스에서는 "metaclass=ABCMeta"를 클래스의 인자로 넣어줘야 한다.

 

추상클래스 구현 형식

from abc import *
class 추상클래스명(metaclass=ABCMeta):

     @abstractmethod
        def 추상메소드(self):
            pass

추상클래스 사용

from abc import *


class AbstractCountry(metaclass=ABCMeta):
    name = '국가명'
    population = '인구'
    capital = '수도'

    def show(self):
        print('국가 클래스의 메소드입니다.')

class Korea(AbstractCountry):

    def __init__(self, name,population, capital):
        self.name = name
        self.population = population
        self.capital = capital

    def show_name(self):
        print('국가 이름은 : ', self.name)
>>> from abstract import *
>>> a = AbstractCountry()
>>> a.show()
국가 클래스의 메소드입니다.
>>> b = Korea("대한민국", 50000000, '서울')
>>> b.show_name()
국가 이름은 :  대한민국

위 코드에서는 추상클래스내에서 추상메서드를 정의하지 않았기 때문에 객체를 생성하더라도 오류가 발생하지 않는다.

 

 

하지만 만약 아래처럼 추상메서드를 추가한다면?

class AbstractCountry(metaclass=ABCMeta):

    ... 생략

    @abstractmethod
    def show_capital(self):
        print('국가의 수도는?')
>>> from abstract import *
>>> a = Korea("대한민국", 50000000, '서울')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Korea with abstract methods show_capital

추상메서드를 추상클래스에서 정의해줬고 자식클래스에서 추상메서드에 대해 추가구현을 해주지 않았다면, 위와 같이 오류가 발생하게 된다. → 추상클래스는 자식클래스에서 추상메서드를 반드시 구현하도록 강제하기 때문!

 

 

그렇다면 자식클래스에서 추상클래스를 정의하고 다시 보자.

class Korea(AbstractCountry):

       def show_capital(self):
           super().show_capital()
           print(self.capital)

        ... 생략
>>> from abstract import *
>>> a = Korea("대한민국", 50000000, '서울')
>>> a.show_capital()
국가의 수도는?
서울

에러없이 객체가 잘 생성되는 것을 확인할 수 있다.


추가

 

>>> from abstract import *
>>> a = AbstractCountry()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class AbstractCountry with abstract methods show_capital

추상메서드를 추가한 상태에서 추상클래스의 객체를 생성하면 오류 발생!

추상클래스는 추상메서드를 만들기 전까지는 기본적인 클래스의 기능을 할 수 있다. 하지만 추상메서드를 추가한 뒤에는 객체를 생성하면 에러가 발생한다.


Reference

https://velog.io/@1yangsh/python-%EC%B6%94%EC%83%81%ED%81%B4%EB%9E%98%EC%8A%A4-abstract-method

 

[python] 추상클래스 (abstract method)

추상클래스란 미구현 추상메소드를 한개 이상 가지며, 자식클래스에서 해당 추상 메소드를 반드시 구현하도록 강제하는 클래스

velog.io

https://wikidocs.net/16075

 

45. class 정리 - 추상클래스(abstract class)

## 1. 추상클래스(abstarct class)란 - 추상클래스란 미구현 추상메소드를 한개 이상 가지며, 자식클래스에서 해당 추상 메소드를 반드시 구현하도록 강제합니다. - …

wikidocs.net