使用 Typing 库
typing 库可帮助为字典、列表等对象以及其中的元素添加类型提示。在本练习中,您将动手练习这些用法。开始吧!
本练习是课程的一部分
Python 面向对象编程进阶
练习说明
- 从
typing库导入Dict和List。 - 使用从
typing导入的类,为roster字典添加类型提示,明确键和值的类型。 - 更新
agents列表的创建方式,为列表对象本身和其所存储元素的类型都添加类型提示。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import Dict and List from typing
from ____ import ____, ____
# Type hint the roster of codenames and number of missions
roster: ____[____, ____] = {
"Chuck": 37,
"Devin": 2,
"Steven": 4
}
# Unpack the values and add type hints for the new list
agents: ____[____] = [
f"Agent {agent}, {missions} missions" \
for agent, missions in roster.items()
]