我使用Enum4库创建一个枚举类如下:
class Color(Enum):
RED = 1
BLUE = 2
我想把[1,2]作为一个列表打印出来。我怎样才能做到这一点呢?
我使用Enum4库创建一个枚举类如下:
class Color(Enum):
RED = 1
BLUE = 2
我想把[1,2]作为一个列表打印出来。我怎样才能做到这一点呢?
当前回答
基于@Jeff的回答,重构为使用类方法,以便您可以对任何枚举重用相同的代码:
from enum import Enum
class ExtendedEnum(Enum):
@classmethod
def list(cls):
return list(map(lambda c: c.value, cls))
class OperationType(ExtendedEnum):
CREATE = 'CREATE'
STATUS = 'STATUS'
EXPAND = 'EXPAND'
DELETE = 'DELETE'
print(OperationType.list())
生产:
['CREATE', 'STATUS', 'EXPAND', 'DELETE']
其他回答
您可以执行以下操作:
[e.value for e in Color]
要对任何类型的值使用Enum,请尝试以下方法: 更新了一些改进…谢谢@杰夫,谢谢你的小费!
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 'GREEN'
BLUE = ('blue', '#0000ff')
@staticmethod
def list():
return list(map(lambda c: c.value, Color))
print(Color.list())
结果:
[1, 'GREEN', ('blue', '#0000ff')]
使用_member_names_快速简单的结果,如果它只是名称,即。
Color._member_names_
还有_member_map_,它返回元素的有序字典。这个函数返回一个集合。OrderedDict,因此您可以使用color . _member_map_items()和color . _member_map_values()。如。
return list(map(lambda x: x.value, Color._member_map_.values()))
将返回颜色的所有有效值
enum类。Enum是一个解决所有枚举需求的类,因此您只需要继承它,并添加自己的字段。然后从那时起,你所需要做的就是调用它的属性:name & value:
from enum import Enum
class Letter(Enum):
A = 1
B = 2
C = 3
print({i.name: i.value for i in Letter})
# prints {'A': 1, 'B': 2, 'C': 3}
使用__members__类方法:
class RoleNames(str, Enum):
AGENT = "agent"
USER = "user"
PRIMARY_USER = "primary_user"
SUPER_USER = "super_user"
@classmethod
def list_roles(cls):
role_names = [member.value for role, member in cls.__members__.items()]
return role_names
>>> role_names = RoleNames.list_roles()
>>> print(role_names)
或者如果你有多个Enum类并且想要抽象类方法:
class BaseEnum(Enum):
@classmethod
def list_roles(cls):
role_names = [member.value for role, member in cls.__members__.items()]
return role_names
class RoleNames(str, BaseEnum):
AGENT = "agent"
USER = "user"
PRIMARY_USER = "primary_user"
SUPER_USER = "super_user"
class PermissionNames(str, BaseEnum):
READ = "updated_at"
WRITE = "sort_by"
READ_WRITE = "sort_order"