2030 Engineer

[파이썬 객체 지향] 추상 클래스 다중 상속 본문

Programming/Python

[파이썬 객체 지향] 추상 클래스 다중 상속

Hard_Try 2020. 2. 18. 17:55
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from abc import ABC, abstractmethod
 
class Message(ABC):
    @abstractmethod
    def print_message(self) -> None:
        pass
 
class Sendable(ABC):
    @abstractmethod
    def send(self, destination: str-> None:
        pass
 
class Email(Message, Sendable):
    def __init__(self, content, user_email):
        self.content = content
        self.user_email = user_email
 
    def print_message(self):
        print("이메일 내용입니다:\n{}".format(self.content))
 
    def send(self, destination):
        print("이메일을 주소 {}에서 {}로 보냅니다!".format(self.user_email, destination))

Message와 Senable을 다중 상속 받는 Email 클래스 예시.

-> 이 표시는 힌트다. 리턴 하는 값의 형태가 무엇이어야 하는지를 알려주는 기능이다.

 

다중상속을 할 경우 추상 클래스는 중복이 되어도 오버라이딩한 것이 결국 내용 반영되기 때문에 문제가 없지만

일반 메소드는 다중 상속할 경우 자식 클래스에서 어느 추상 클래스의 일반 메소드를 실행해야하는지 애매모호해지므로 주의해야한다. 파이썬에서는 mro라는 규칙에 의해 실행되므로 더더욱 주의해야 한다.

Comments