类型提示枚举 属性 returns 该枚举的一个实例
Type hinting an enum property that returns an instance of that 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)
我正在尝试键入提示 left
和 right
属性以指示它们的 return 值是 Direction
.
类型
我认为上面的方法可行,但是当我 运行 代码时,我收到以下错误:NameError: name 'Direction' is not defined
。我猜这是因为 Python 解释器在定义此函数时还不知道 Direction
枚举是什么。
我的问题是,无论如何我可以键入提示这些属性吗?谢谢。
这被称为前向引用,因为在执行 属性 函数签名时方向 class 尚未定义。您需要将前向参考用引号引起来。有关详细信息,请参阅 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)
我有一个如下所示的枚举:
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)
我正在尝试键入提示 left
和 right
属性以指示它们的 return 值是 Direction
.
我认为上面的方法可行,但是当我 运行 代码时,我收到以下错误:NameError: name 'Direction' is not defined
。我猜这是因为 Python 解释器在定义此函数时还不知道 Direction
枚举是什么。
我的问题是,无论如何我可以键入提示这些属性吗?谢谢。
这被称为前向引用,因为在执行 属性 函数签名时方向 class 尚未定义。您需要将前向参考用引号引起来。有关详细信息,请参阅 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)