Python 3.x 类型暗示返回该枚举实例的枚举属性
我有一个如下所示的枚举:Python 3.x 类型暗示返回该枚举实例的枚举属性,python-3.x,enums,type-hinting,Python 3.x,Enums,Type Hinting,我有一个如下所示的枚举: 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 r
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
属性,以指示其返回值的类型为Direction
我原以为上面的方法行得通,但当我运行代码时,我得到了以下错误:namererror:name'Direction'未定义
。我猜这是因为Python解释器在定义这个函数时还不知道枚举的方向是什么
我的问题是,我是否可以键入这些属性?谢谢。这被称为正向引用,因为在执行属性函数签名时还没有定义方向类。你需要用引号把推荐信引出来。有关更多信息,请参阅
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)
Python3.8允许转发引用,如果您从未来导入注释,或者只引用类型,例如,
“方向”
。在Py3.8中,您可以使用来自未来导入注释,那么这些转发声明就不需要引用。谢谢!这正是我需要的信息@AChampion我正在使用Python3.8,因此我将利用注释
。感谢你的建议。