Python相当于C#Enum.HasFlag

时间:2014-08-27 04:37:22

标签: python enums

让我们在python中说

StateA = 1
StateB = 2
StateC = StateA | StateB

...
instance.state = StateA

在C#中,Enum中有一个HasFlag函数,它告诉我一个对象的标志是StateC的一部分

python中有相同的版本吗?

现在我只能想到(作为按位菜鸟),甚至不确定它是否应该起作用:

if instance.state | StateC == StateC:
    # yes in StateC

3 个答案:

答案 0 :(得分:2)

测试标志:

value & flag == flag

添加标志:

value |= flag

清除旗帜:

value &= ~flag

答案 1 :(得分:1)

HasFlag基本上是按位操作。

>>> a = 0b01
>>> b = 0b10
>>> "{0:b}".format(a | b,)
'11'
>>> def has_flag(v, flag): return v & flag == flag
...
>>> has_flag(0b111, a)
True
>>> has_flag(0b111, a|b)
True
>>> has_flag(0b1, a|b)
False

答案 2 :(得分:1)

Python 3.4 有一个Enum data typehas been backported

from enum import Enum

class States(Enum):
    StateA = 1
    StateB = 2
    StateC = StateA | StateB
    def has_flag(self, flag):
        return self.value & flag.value

if States.StateC.has_flag(States.StateA):
    print("yup, it's there!")

Python 3.6 拥有(Int)Flag data typethe aenum1 library中也存在{<3}}:

from enum import Flag  # or from aenum import Flag

class States(Flag):
    StateA = 1
    StateB = 2
    StateC = StateA | StateB

if States.StateA in States.StateC:
    print("yup, it's there!")

1 披露:我是Python stdlib Enumenum34 backportAdvanced Enumeration (aenum)图书馆的作者。