Menu
CoddyTech

里氏替换

Coddy Clean Code:用 Python 写出更好的代码 课程的第 24 课,共 28 课。

“使用基类指针或引用的函数,必须能够使用派生类的对象,而无需知道这些对象属于派生类。”

这个原则指出,子类必须能够替代其父类。

例如:

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}')

正如你所看到的,SMS 和 Email 都继承自 Notification,但一个发送到 email,另一个发送到 phone。SMS 类无法替代其父类 Notification!

challenge icon

挑战

中等

修复给定的代码,以应用里氏替换原则。

- notify 函数应只接收 message 作为参数。

- Email 和 SMS 都应有一个构造函数,分别用于初始化 email 和 phone。

- 修改代码以应用这些更改。

 

这只是应用里氏替换原则的一种建议答案,还有其他可行的答案!

亲手试试

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 写出更好的代码中的所有课

自己练习: Python 在线编译器