我使用Enum4库创建一个枚举类如下:
class Color(Enum):
RED = 1
BLUE = 2
我想把[1,2]作为一个列表打印出来。我怎样才能做到这一点呢?
我使用Enum4库创建一个枚举类如下:
class Color(Enum):
RED = 1
BLUE = 2
我想把[1,2]作为一个列表打印出来。我怎样才能做到这一点呢?
当前回答
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"
要对任何类型的值使用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')]
你可以有一个这样的SuperEnum:
from enum import Enum
class SuperEnum(Enum):
@classmethod
def to_dict(cls):
"""Returns a dictionary representation of the enum."""
return {e.name: e.value for e in cls}
@classmethod
def keys(cls):
"""Returns a list of all the enum keys."""
return cls._member_names_
@classmethod
def values(cls):
"""Returns a list of all the enum values."""
return list(cls._value2member_map_.keys())
像这样使用它:
class Roles(SuperEnum):
ADMIN = 1
USER = 2
GUEST = 3
所以你可以:
Roles.to_dict() # {'ADMIN': 1, 'USER': 2, 'GUEST': 3}
Roles.keys() # ['ADMIN', 'USER', 'GUEST']
Roles.values() # [1, 2, 3]
使用_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()))
将返回颜色的所有有效值
您可以执行以下操作:
[e.value for e in Color]