将整数解释为枚举标志 [英] interpret an integer as enum flags
本文介绍了将整数解释为枚举标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的Flag枚举:
Suppose I have a Flag enum like this:
From enum import Flag
class suspicion(Flag):
TOT_PCNT_LOW = 1
IND_PCNT_LOW = 2
IND_SCORE_LOW = 4
假设我有一个使用这些标志构造的整数
And suppose I have an integer that was constructed using these flags
i = suspicion.IND_PCNT_LOW.value | suspicion.TOT_PCNT_LOW.value # i == 3
如何获取整数中设置的标志名称的列表?例如:
How do I get a list of the names of the flags that are set in the integer? For example:
print(some_method(i)) # prints ["IND_PCNT_LOW", "TOT_PCNT_LOW"]
推荐答案
设置代码:
from enum import Flag
class Suspicion(Flag):
TOT_PCNT_LOW = 1
IND_PCNT_LOW = 2
IND_SCORE_LOW = 4
a_flag = Suspicion.TOT_PCNT_LOW | Suspicion.IND_PCNT_LOW
在3.10之前的Python中
In Python before 3.10
def flag_names(flag):
return [f.name for f in flag.__class__ if f & flag == f]
在3.10及更高版本中,它会更容易
It's slightly easier in 3.10+
def flag_names(flag):
# Python 3.10+
return [f.name for f in flag]
无论哪种情况:
In either case:
print(flag_names(a_flag))
得到你
['TOT_PCNT_LOW', 'IND_PCNT_LOW']
如果传入的 flag
参数可以是整数而不是 Suspicion
成员,则您也可以处理该问题:
If the incoming flag
argument may be an integer instead of a Suspicion
member, you can handle that as well:
def flag_names(flag, enum=None):
"""
returns names of component flags making up flag
if `flag` is an integer, `enum` must be enumeration to match against
"""
if enum is None and not isinstance(flag, Flag):
raise ValueError('`enum` must be specifed if `flag` is an `int`')
enum = enum or flag.__class__
return [f.name for f in enum if f & flag == f]
这篇关于将整数解释为枚举标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文