處理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中文網其他相關文章!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3漢化版
中文版,非常好用

Dreamweaver CS6
視覺化網頁開發工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

WebStorm Mac版
好用的JavaScript開發工具