首页 > 解决方案 > 0 项的 Python IntFlags 行为

问题描述

在以下Python3中使用IntFlag的示例代码中,我可以理解前 5 个行为。enum但我无法理解最后三种行为。我想这些结果应该是False。谁能详细说明这些行为?并且知道如何定义使 3 个结果为“假”的 CLEAR 吗?

In [3]: from enum import IntFlag, auto

In [4]: class Functions(IntFlag):
   ...:     CLEAR=0
   ...:     FUNC1=auto()
   ...:     FUNC2=auto()
   ...:     FUNC3=auto()
   ...:     FUNC12=FUNC1|FUNC2
   ...:     ALL=FUNC1|FUNC2|FUNC3
   ...:

In [5]: Functions.FUNC1 in Functions.FUNC12 #OK
Out[5]: True

In [6]: Functions.FUNC2 in Functions.FUNC12 #OK
Out[6]: True

In [7]: Functions.FUNC3 in Functions.FUNC12 #OK
Out[7]: False

In [8]: Functions.FUNC12 in Functions.ALL #OK
Out[8]: True

In [9]: Functions.ALL in Functions.FUNC12 #OK
Out[9]: False

In [10]: Functions.CLEAR in Functions.ALL #?
Out[10]: True

In [11]: Functions.CLEAR in Functions.FUNC12 #??
Out[11]: True

In [12]: Functions.CLEAR in Functions.FUNC1 #???
Out[12]: True

标签: pythonpython-3.xenumsenum-flags

解决方案


CLEAR表示空的标志集。

文档似乎从未明确提及这一点,但据我了解,操作员会in测试左侧的标志是否是右侧的子集。

但是,该方法的源代码Flag.__contains__(由 继承IntFlag)支持这种理解——该方法实现了操作other in self

def __contains__(self, other):
    """
    Returns True if self has at least the same flags set as other.
    """
    if not isinstance(other, self.__class__):
        raise TypeError(
            "unsupported operand type(s) for 'in': '%s' and '%s'" % (
                type(other).__qualname__, self.__class__.__qualname__))
    return other._value_ & self._value_ == other._value_

空集是任何其他集的子集,因此Functions.CLEAR in Functions.x对于任何 都是正确的x

或者,就执行的具体按位运算而言,CLEAR为 0,因此CLEAR in x评估0 & x == 0始终为真。


推荐阅读