[英]Create an enum class from a list of strings in Python
When I run this当我运行这个
from enum import Enum
class MyEnumType(str, Enum):
RED = 'RED'
BLUE = 'BLUE'
GREEN = 'GREEN'
for x in MyEnumType:
print(x)
I get the following as expected:我按预期得到以下信息:
MyEnumType.RED
MyEnumType.BLUE
MyEnumType.GREEN
Is it possible to create a class like this from a list or tuple that has been obtained from elsewhere?是否可以从从其他地方获得的列表或元组创建这样的 class?
Something vaguely similar to this perhaps:也许与此有些相似:
myEnumStrings = ('RED', 'GREEN', 'BLUE')
class MyEnumType(str, Enum):
def __init__(self):
for x in myEnumStrings :
self.setattr(self, x,x)
However, in the same way as in the original, I don't want to have to explicitly instantiate an object.但是,与原始方法一样,我不想显式实例化 object。
You can use the enum functional API for this:您可以为此使用枚举函数 API :
from enum import Enum
myEnumStrings = ('RED', 'GREEN', 'BLUE')
MyEnumType = Enum('MyEnumType', myEnumStrings)
From the docs:从文档:
The first argument of the call to Enum is the name of the enumeration.
调用 Enum 的第一个参数是枚举的名称。
The second argument is the source of enumeration member names.
第二个参数是枚举成员名称的来源。 It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (eg dictionary) of names to values.
它可以是以空格分隔的名称字符串、名称序列、具有键/值对的二元组序列或名称到值的映射(例如字典)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.