Menu
Coddy logo textTech

리스코프 치환 원칙

Coddy의 Clean Code - Python으로 더 나은 코드 작성하기 코스 레슨 — 28개 중 24번째.

"기본 클래스에 대한 포인터나 참조를 사용하는 함수는 파생 클래스의 객체를 알지 못해도 사용할 수 있어야 합니다."

이 원칙은 자식 클래스가 부모 클래스를 대체할 수 있어야 함을 명시합니다.

예를 들어,

class Notification(ABC):
	@abstractmethod
	def notify(self, message, email):
		pass


class Email(Notification):
	def notify(self, message, email):
		print(f'Send {message} to {email}')


class SMS(Notification):
	def notify(self, message, phone):
		print(f'Send {message} to {phone}')

보시다시피 SMSEmail 모두 Notification을 상속받지만, 하나는 email로 보내고 다른 하나는 phone으로 보냅니다. 따라서 SMS 클래스는 부모인 Notification을 대체할 수 없습니다!

challenge icon

챌린지

중급

주어진 코드를 수정하여 리스코프 치환 원칙(Liskov substitution principle)을 적용하세요 -

- notify 함수는 message만 인자로 받아야 합니다.

- EmailSMS는 각각 emailphone을 적절히 초기화하는 생성자를 가져야 합니다.

- 변경 사항을 적용하도록 코드를 수정하세요

 

이것은 리스코프 원칙을 적용하기 위한 하나의 제안된 해결책일 뿐이며, 작동하는 다른 방법들도 있습니다!

직접 해보기

from abc import ABC, abstractmethod


class Notification(ABC):
    @abstractmethod
    def notify(self, message, email):
        pass


class Email(Notification):
    def notify(self, message, email):
        print(f'Send {message} to {email}')


class SMS(Notification):
    def notify(self, message, phone):
        print(f'Send {message} to {phone}')


if __name__ == '__main__':
    email = input()
    phone = input()
    message = input()
    notification1 = Email()
    notification2 = SMS()
    notification1.notify(message, email)
    notification2.notify(message, phone)

Clean Code - Python으로 더 나은 코드 작성하기의 모든 레슨