类型提示返回该枚举的实例的枚举属性



我有一个枚举,看起来像这样:

class Direction(Enum):
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
@property
def left(self) -> Direction:
new_direction = (self.value - 1) % 4
return Direction(new_direction)
@property
def right(self) -> Direction:
new_direction = (self.value + 1) % 4
return Direction(new_direction)

我正在尝试键入提示leftright属性以指示它们的返回值为Direction类型。

我认为上述方法可以工作,但是当我运行代码时,出现以下错误:NameError: name 'Direction' is not defined。我想这是因为 Python 解释器在定义这个函数时还不知道Direction枚举是什么。

我的问题是,无论如何我都可以键入提示这些属性吗?谢谢。

这称为前向引用,因为在执行属性函数签名时尚未定义 Direction 类。您需要将前向引用放在引号中。有关详细信息,请参阅 https://www.python.org/dev/peps/pep-0484/#forward-references。

from enum import Enum
class Direction(Enum):
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
@property
def left(self) -> 'Direction':
new_direction = (self.value - 1) % 4
return Direction(new_direction)
@property
def right(self) -> 'Direction':
new_direction = (self.value + 1) % 4
return Direction(new_direction)

最新更新