首页 > 解决方案 > 在 Python 中修改枚举类

问题描述

from enum import Enum

class Direction(Enum):
    NORTH = 0
    EAST = 1
    SOUTH = 2
    WEST = 3

    def turn_right(self):
        self = Direction((self.value + 1) % 4)

d = Direction.EAST
print(d)
d.turn_right()
print(d)
d.turn_right()
print(d)

预期的输出应该是

Direction.EAST
Direction.SOUTH
Direction.WEST

每一回合之后,但我得到的只是

Direction.EAST
Direction.EAST
Direction.EAST

好像没有更新self,为什么呢?如何更改类以使其用法保持不变?

一种可能的解决方法是

    def turn_right(self):
        return Direction((self.value + 1) % 4)

但这Direction每次都会返回一个新的,有没有办法让该方法“就地”工作?

标签: pythonpython-3.x

解决方案


推荐阅读