Menu
CoddyTech

回顾:按行为派发

Coddy 面向 C# 开发者的 Python 课程 课程的第 42 课,共 48 课。

challenge icon

挑战

入门

实现 Email.send(text),返回 email: 加上 text,以及实现 Sms.send(text),返回 sms: 加上 text。实现 Dispatcher(channels),保存列表的浅拷贝,其 dispatch(text) 方法按原始顺序返回每个通道的一个结果。主程序读取 email/sms/log 标记和一条消息,提供其自身的 log 对象,创建 dispatcher,并在分发前清空原始列表。重复项保持重复。它会输出结果;若没有通道则输出 none。所有方法仅格式化字符串;不会实际发送任何消息。

C# 迁移检查点

就像 List<T> 的拷贝构造函数一样,Python 浅拷贝可以在保留通道对象的同时隔离外层列表的修改。

C# 参考摘录:可执行语句假设使用了 using System;仅包含类型的摘录展示了声明的契约。

var channels = new System.Collections.Generic.List<string> { "email" };
var stored = new System.Collections.Generic.List<string>(channels);
channels.Clear();
Console.WriteLine(stored.Count);

Python 模式

channels = ["email"]
stored = channels.copy()
channels.clear()
print(len(stored))

可编辑的实现文件:email.py、sms.py、dispatcher.py。被锁定的 driver.py 是提供的启动器或输入/输出框架,必须保持不变。

保留提供的导入和确切的 API 名称。返回结果或抛出所需异常;不要在这些实现模块中读取输入或打印输出。

亲手试试

from email import Email
from sms import Sms
from dispatcher import Dispatcher

class Log:
    def send(self, text):
        return "log:" + text

factories = {"email": Email, "sms": Sms, "log": Log}
channels = [factories[name]() for name in input().split()]
text = input()
dispatcher = Dispatcher(channels)
channels.clear()
results = dispatcher.dispatch(text)
if not results:
    print("none")
for result in results:
    print(result)

面向 C# 开发者的 Python 课程中的所有课

自己练习: Python 在线编译器