我使用Enum4库创建一个枚举类如下:

class Color(Enum):
    RED = 1
    BLUE = 2

我想把[1,2]作为一个列表打印出来。我怎样才能做到这一点呢?


当前回答

一种方法是获取_value2member_map_属性的键值:

class Color(Enum):
    RED = 1
    BLUE = 2

list(Color._value2member_map_.keys())
# [1, 2]

其他回答

要对任何类型的值使用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')]

使用__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类。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}

一种方法是获取_value2member_map_属性的键值:

class Color(Enum):
    RED = 1
    BLUE = 2

list(Color._value2member_map_.keys())
# [1, 2]

您可以执行以下操作:

[e.value for e in Color]