我想在Enum
中添加一个查找列表作为静态变量。我能做的最好的是
class Seed(IntEnum):
HEARTS = 0
DIAMONDS = 1
SPADES = 2
CLUBS = 3
@staticmethod
def value_list():
Seed.list = [s.value for s in Seed]
然后在代码中我必须要做的
Seed.value_list()
初始化变量list
,该变量不是静态的,但对于所有实例都相同。然后我可以使用
Seed.list
有没有办法做到这一点?
答案 0 :(得分:3)
您可以编写一个类decorator:
def values_list(enum_cls):
# create the values_list attribute and then return the class
enum_cls.values_list = [member.value for member in enum_cls]
return enum_cls
@values_list
class Seed(IntEnum):
HEARTS = 0
DIAMONDS = 1
SPADES = 2
CLUBS = 3
print(Seed.values_list)
# [0, 1, 2, 3]
答案 1 :(得分:1)
您需要返回值列表:
from enum import IntEnum
class Seed(IntEnum):
HEARTS = 0
DIAMONDS = 1
SPADES = 2
CLUBS = 3
@classmethod
def values(cls):
return [s.value for s in cls]
if __name__ == '__main__':
print(Seed.values())
[0, 1, 2, 3]