开始使用免费开始使用

使用 Typing 库

typing 库可帮助为字典、列表等对象以及其中的元素添加类型提示。在本练习中,您将动手练习这些用法。开始吧!

本练习是课程的一部分

Python 面向对象编程进阶

查看课程

练习说明

  • typing 库导入 DictList
  • 使用从 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()
]
编辑并运行代码