如何在 Python 中使用按位标志

Chr*_*isz 3 python bitflags python-2.7

from enum import Enum

class InputTypes(Enum):
    """
    Flags to represent the different kinds of input we
    are acting on from the user
    """
    KEYBOARD = 0b00000001,
    MOUSE_BUTTONS = 0b00000010,
    MOUSE_MOVE = 0b00000100,
    ALL = 0b11111111


if __name__ == "__main__":
    x = (InputTypes.KEYBOARD | InputTypes.MOUSE_BUTTONS)
Run Code Online (Sandbox Code Playgroud)

我收到错误:

TypeError: unsupported operand type(s) for |: 'InputTypes' and 'InputTypes'
Run Code Online (Sandbox Code Playgroud)

如何在 python 2.7 和 python3 中正确定义一些标志并使用它们?

Eth*_*man 5

对于 Python 2,您想使用aenum(Advanced Enum) 1。如果数值不重要,您可以使用Flag

from aenum import Flag, auto

class InputTypes(Flag):
    """
    Flags to represent the different kinds of input we
    are acting on from the user
    """
    KEYBOARD = auto()
    MOUSE_BUTTONS = auto()
    MOUSE_MOVE = auto()
    ALL = KEYBOARD | MOUSE_BUTTONS | MOUSE_MOVE
Run Code Online (Sandbox Code Playgroud)

如果这些值很重要(意味着您将使用它们作为整数),请IntFlag改为使用。


1声明:我是Python stdlibEnumenum34backportAdvanced Enumeration ( aenum)库的作者 。