首頁 >後端開發 >Python教學 >如何正確處理 Python 中封閉類別的型別提示?

如何正確處理 Python 中封閉類別的型別提示?

Barbara Streisand
Barbara Streisand原創
2024-12-18 00:35:11386瀏覽

How Can I Properly Handle Type Hints for Enclosed Classes in Python?

處理Python 中封閉類別的型別提示

理解問題

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 3.10 中,推遲對註釋的評估原計劃成為預設設置,但此後已推遲到未來版本。

以上是如何正確處理 Python 中封閉類別的型別提示?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn