開始使用免費開始

使用 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()
]
編輯並執行程式碼