如何通过其对应的数字返回枚举的值?

时间:2019-01-22 13:03:22

标签: python enums

我应该如何实现func来正确返回Direction枚举的相应值?

class Direction(Enum):
    right = 0
    down = 1
    left = 2
    up = 3

    def func(self, n):
        # When n = 0 return Direction.right
        # When n = 1 return Direction.down
        # When n = 2 return Direction.left
        # When n = 3 return Direction.up

1 个答案:

答案 0 :(得分:1)

不需要功能,可以像这样简单地完成:

>>> Direction(1)
<Direction.down: 1>
>>> Direction(3)
<Direction.up: 3>

来源:https://docs.python.org/3.4/library/enum.html