ruohola
ruohola

Reputation: 24107

How to return enum's value by its corresponding number?

How should I implement func to correctly return the corresponding value of the Direction enum?

from enum import Enum

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

Upvotes: 0

Views: 83

Answers (1)

ruohola
ruohola

Reputation: 24107

A function is not needed, it can simply be done like this:

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

Source: https://docs.python.org/3.4/library/enum.html

Upvotes: 1

Related Questions