python - 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
解决方案
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
始终为真。
推荐阅读
- javascript - 如何打破一个字符串,使其不在我的源代码中的一行中?
- python - 某些模块似乎不适用于 pyw。(但它适用于 py)
- angular - 动态使用 svg 文件并在角度 9 中动态更改颜色
- swift - 如何将 NSManagedObject 转换为 NSItemProviderWriting/NSItemProviderReading?
- c# - Windows 服务无法从 c:\windows\system32\foldername 读取/观看
- javascript - 你如何在反应打字稿中根据需要标记道具?
- python - Unable to install Numpy Getting 由于 EnvironmentError: HTTPSConnectionPool 无法安装包
- ruby - Jekyll kramdown 数学渲染设置
- c - 如何在 C 中将字符串 (A) 分配为另一个字符串 (B)
- c# - 将键盘键分配给按钮单击 WINFORM