从 Python 中的字符串列表创建枚举 class
Create an enum class from a list of strings in Python
当我运行这个
from enum import Enum
class MyEnumType(str, Enum):
RED = 'RED'
BLUE = 'BLUE'
GREEN = 'GREEN'
for x in MyEnumType:
print(x)
我得到了预期的结果:
MyEnumType.RED
MyEnumType.BLUE
MyEnumType.GREEN
是否可以从从其他地方获得的列表或元组创建这样的 class?
可能有点类似于:
myEnumStrings = ('RED', 'GREEN', 'BLUE')
class MyEnumType(str, Enum):
def __init__(self):
for x in myEnumStrings :
self.setattr(self, x,x)
但是,和原来一样,我不想显式地实例化一个对象。
您可以为此使用 enum functional API:
from enum import Enum
myEnumStrings = ('RED', 'GREEN', 'BLUE')
MyEnumType = Enum('MyEnumType', myEnumStrings)
来自文档:
The first argument of the call to Enum is the name of the enumeration.
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 (e.g. dictionary) of names to values.
当我运行这个
from enum import Enum
class MyEnumType(str, Enum):
RED = 'RED'
BLUE = 'BLUE'
GREEN = 'GREEN'
for x in MyEnumType:
print(x)
我得到了预期的结果:
MyEnumType.RED
MyEnumType.BLUE
MyEnumType.GREEN
是否可以从从其他地方获得的列表或元组创建这样的 class?
可能有点类似于:
myEnumStrings = ('RED', 'GREEN', 'BLUE')
class MyEnumType(str, Enum):
def __init__(self):
for x in myEnumStrings :
self.setattr(self, x,x)
但是,和原来一样,我不想显式地实例化一个对象。
您可以为此使用 enum functional API:
from enum import Enum
myEnumStrings = ('RED', 'GREEN', 'BLUE')
MyEnumType = Enum('MyEnumType', myEnumStrings)
来自文档:
The first argument of the call to Enum is the name of the enumeration.
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 (e.g. dictionary) of names to values.