
- FastAPI 教程
- FastAPI - 首頁
- FastAPI - 簡介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 型別提示
- FastAPI - IDE 支援
- FastAPI - REST 架構
- FastAPI - 路徑引數
- FastAPI - 查詢引數
- FastAPI - 引數驗證
- FastAPI - Pydantic
- FastAPI - 請求體
- FastAPI - 模板
- FastAPI - 靜態檔案
- FastAPI - HTML 表單模板
- FastAPI - 訪問表單資料
- FastAPI - 上傳檔案
- FastAPI - Cookie 引數
- FastAPI - 頭部引數
- FastAPI - 響應模型
- FastAPI - 巢狀模型
- FastAPI - 依賴項
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 資料庫
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - Websockets
- FastAPI - FastAPI 事件處理器
- FastAPI - 掛載子應用
- FastAPI - 中介軟體
- FastAPI - 掛載 Flask 應用
- FastAPI - 部署
- FastAPI 有用資源
- FastAPI - 快速指南
- FastAPI - 有用資源
- FastAPI - 討論
FastAPI - IDE 支援
Python 的型別提示功能在幾乎所有IDE(整合開發環境),例如PyCharm和VS Code中得到最有效的利用,以提供動態自動完成功能。
讓我們看看 VS Code 如何使用型別提示在編寫程式碼時提供自動完成建議。在下面的示例中,定義了一個名為sayhello的函式,其中 name 作為引數。該函式透過在兩者之間新增空格將“Hello”與 name 引數連線起來,從而返回一個字串。此外,還需要確保 name 的首字母大寫。
Python 的str類具有用於此目的的capitalize()方法,但是如果在鍵入程式碼時不記得它,則必須在其他地方搜尋它。如果在 name 後面加一個點,您期望看到屬性列表,但什麼也沒有顯示,因為 Python 不知道 name 變數的執行時型別是什麼。

在這裡,型別提示派上用場。在函式定義中包含 name 的型別 str。現在,當您在 name 後按點 (.) 時,將出現所有字串方法的下拉列表,從中可以選擇所需的方法(在本例中為 capitalize())。

也可以將型別提示與使用者定義的類一起使用。在下面的示例中,定義了一個矩形類,其中包含__init__()建構函式的引數的型別提示。
class rectangle: def __init__(self, w:int, h:int) ->None: self.width=w self.height=h
以下是一個使用上述矩形類的物件作為引數的函式。宣告中使用的型別提示是類的名稱。
def area(r:rectangle)->int: return r.width*r.height r1=rectangle(10,20) print ("area = ", area(r1))
在這種情況下,IDE 編輯器也提供了自動完成支援,提示例項屬性列表。以下是PyCharm編輯器的螢幕截圖。

FastAPI廣泛使用型別提示。此功能隨處可見,例如路徑引數、查詢引數、頭部、主體、依賴項等,以及驗證來自傳入請求的資料。OpenAPI 文件生成也使用型別提示。
廣告