多分支登录的标志用法

2024-03-29 01:26:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要这样做:

from enum import Flag, auto

class WISENESS(Flag):
    Y = auto()
    M = auto()
    D = auto()
    YM = Y | M
    YD = Y | D
    MD = M | D
    YMD = Y | M | D

first_case = WISENESS.Y

first_case == WISENESS.Y # True
first_case == WISENESS.M # False
first_case == WISENESS.D # False

###

second_case = WISENESS.YD

second_case == WISENESS.Y # True
second_case == WISENESS.M # False
second_case == WISENESS.D # True

####

third_case = WISENESS.YMD

third_case == WISENESS.Y # True
third_case == WISENESS.M # True
third_case == WISENESS.D # True

也就是说,根据标志值,在某些情况下它将是真的。例如,我可能需要对所有可能的情况执行一个操作,或者只对其中两个执行一个操作。 就像这个例子:

if WISENESS.Y:
    do_something_in_case_of_Y_or_MY_or_YD_or_YMD()
if WISENESS.M:
    do_something_in_case_of_M_or_MD_or_YM_or_YMD()
if WISENESS.D:
    do_something_in_case_of_D_or_MD_or_YD_or_YMD()

我试图在标准库中使用enum模块中的Flag,猜想它在这种情况下对我有帮助,但要么我不理解它是如何工作的,要么我必须以不同的方式实现我的目标。你知道吗


Tags: orfalsetrueautoif情况mdfirst
2条回答

检查Flag成员身份的内置方法是使用标准Python in操作符:

>>> second_case in WISENESS.Y
True

最后一个例子是:

some_flag = ...

if WISENESS.Y in some_flag:
    do_something_in_case_of_Y_or_MY_or_YD_or_YMD()
if WISENESS.M in some flag:
    do_something_in_case_of_M_or_MD_or_YM_or_YMD()
if WISENESS.D in some flag:
    do_something_in_case_of_D_or_MD_or_YD_or_YMD()

注:关于这个问题的正确的Pythonic方法,请参见Ethan Furman的答案。这个答案解释了如何使用位运算符检查标志包含,这在其他情况和其他编程语言中很有用。你知道吗

要检查值中是否包含标志,应使用位运算符,特别是&。你知道吗

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')

&AND运算符通过返回所提供的两个值中的相同位来工作。在枚举定义中,auto()提供值Y = 1M = 2D = 4,这些值在二进制中分别是000100100100。然后,组合值包含来自它们包含的每个标志的位,这些位由|或运算符形成,例如MD = 0010 | 0100 = 0110。你知道吗

在上面的代码中,如果wiseness0110,则进行以下&检查:

wiseness & WISENESS.Y  > 0110 & 0001 = 0000  > != WISENESS.Y
wiseness & WISENESS.M  > 0110 & 0010 = 0010  > == WISENESS.M
wiseness & WISENESS.D  > 0110 & 0100 = 0100  > == WISENESS.D

相关问题 更多 >