使用 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()
]