理解問題
class 作為其封閉類別的方法時定義其傳回類型,您可能會遇到未解決的參考錯誤。讓我們考慮一下 Python 3 中的以下程式碼:
class Position: def __init__(self, x: int, y: int): self.x = x self.y = y def __add__(self, other: Position) -> Position: return Position(self.x + other.x, self.y + other.y)
此程式碼失敗並出現 NameError,因為 Position 類別未在 __add__ 方法的範圍內定義。
解決問題
有「Self」的Python 3.11型別:
在Python 3.11 及更高版本中,您可以使用Self類型在型別提示中引用封閉類別:
from typing import Self class Position: def __add__(self, other: Self) -> Self: return Position(self.x + other.x, self.y + other.y)
Python 3.7 with '__future__匯入註解':
如果您使用的是 Python 3.7或新版本中,您可以透過新增以下導入語句來啟用註解的延遲評估:
from __future__ import annotations
啟用此功能後,類型提示將儲存為字串,直到模組完全加載,從而解決引用問題:
class Position: def __add__(self, other: Position) -> Position: return Position(self.x + other.x, self.y + other.y)
Python
對於Python 版本在3.7以下,您可以使用單引號指定對封閉類別的字串參考:
class Position: def __add__(self, other: 'Position') -> 'Position': return Position(self.x + other.x, self.y + other.y)
這將建立一個前向引用,一旦定義了類別,該引用將被解析。
附加說明:
以上是如何正確處理 Python 中封閉類別的型別提示?的詳細內容。更多資訊請關注PHP中文網其他相關文章!