擅长:python、mysql、java
<p>注:关于这个问题的正确的Pythonic方法,请参见Ethan Furman的答案。这个答案解释了如何使用位运算符检查标志包含,这在其他情况和其他编程语言中很有用。你知道吗</p>
<p>要检查值中是否包含标志,应使用位运算符,特别是<code>&</code>。你知道吗</p>
<pre><code>wiseness = WISENESS.MD
if wiseness & WISENESS.Y == WISENESS.Y:
print('contains Y')
if wiseness & WISENESS.M == WISENESS.M:
print('contains M')
if wiseness & WISENESS.D == WISENESS.D:
print('contains D')
</code></pre>
<p><code>&</code>AND运算符通过返回所提供的两个值中的相同位来工作。在枚举定义中,<code>auto()</code>提供值<code>Y = 1</code>、<code>M = 2</code>、<code>D = 4</code>,这些值在二进制中分别是<code>0001</code>、<code>0010</code>和<code>0100</code>。然后,组合值包含来自它们包含的每个标志的位,这些位由<code>|</code>或运算符形成,例如<code>MD = 0010 | 0100 = 0110</code>。你知道吗</p>
<p>在上面的代码中,如果<code>wiseness</code>是<code>0110</code>,则进行以下<code>&</code>检查:</p>
<pre><code>wiseness & WISENESS.Y > 0110 & 0001 = 0000 > != WISENESS.Y
wiseness & WISENESS.M > 0110 & 0010 = 0010 > == WISENESS.M
wiseness & WISENESS.D > 0110 & 0100 = 0100 > == WISENESS.D
</code></pre>