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

问题描述 投票:0回答:1

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

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枚举是什么。

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

python-3.x enums type-hinting
1个回答
1
投票

这被称为前向引用,因为执行属性函数签名时尚未定义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)
© www.soinside.com 2019 - 2024. All rights reserved.