我正在使用泛型在 python 中創建一個 List 類(類似 java 串列的 List)。類節點也是通用的,我正在為 prev 和 next 節點創建 getter 和 setter 方法。我想知道如何回傳類節點本身這樣的型別?這是我的進步:
from typing import Generic, TypeVar
T = TypeVar('T')
class Node(Generic[T]):
''' Generic class Node. It models a node for a linked list. '''
def __init__(self, element: T) -> None:
''' Constructor. It recives an element of type T.'''
self.element = element
self.next = None
self.prev = None
def get_item(self) -> T:
''' Returns the item in the node.'''
return self.element
def get_prev(self) -> #What is the type I should return here?:
''' Returns the previous node.'''
return self.prev
def get_next(self) -> #What is the type I should return here?:
''' Return the next node.'''
return self.next
def set_prev(self, prev) -> None:
''' Changes the previous element to the specified node.'''
self.prev = prev
def set_next(self, next) -> None:
''' Changes the next element to the specified node.'''
self.next = next
我試過了
def get_prev(self) -> Node[T]:
''' Returns the previous node.'''
return self.prev
def get_next(self) -> Node[T]:
''' Return the next node.'''
return self.next
但它給了我錯誤
Traceback (most recent call last):
File "List.py", line 5, in <module>
class Node(Generic[T]):
File "List.py", line 18, in Node
def get_prev(self) -> Node[T]:
NameError: name 'Node' is not defined
uj5u.com熱心網友回復:
我認為最新的 Python 版本具有在型別注釋中自參考類的能力(這里是當前正在定義get_prev的回傳型別)。Node
較舊的 Python 版本(低至 3.7)仍然通過添加以下內容來支持它:
from __future__ import annotations
見:https ://peps.python.org/pep-0563/#enabling-the-future-behavior-in-python-3-7
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470413.html
