您可以向Enum 对象添加属性,也可以使用dict 映射Enum。还有其他选项,但这些似乎最简单。
假设您有 Tree、Rock、Flower 等类,对应于 Enum 的值:
class Tree:
def __init__(self, height, coords):
pass
class Rock:
def __init__(self, coords):
pass
class Flower:
def __init__(self, color, iscarnivore, coords):
pass
我专门展示了一个扩展版本,其中每个类都有不同的初始化程序和一组不同的默认值。如果它们都相同,请使用现有答案。
选项 1 是这样定义枚举:
class Entities(Enum):
TREE = (Tree, 100, (0, 0))
ROCK = (Rock, (0, 0))
FLOWER = (Flower, 'red', True, (0, 0))
def __new__(cls, t, *args):
obj = object.__new__(cls)
obj._value_ = len(cls.__members__) + 1
obj.type = t
obj.defaults = args
return obj
def init(self):
return self.type(*self.defaults)
现在,my_func 只是枚举本身的 init 方法:
>>> FLOWER.init() # Calls Flower('red', False, (0, 0))
第二个选项是将Enum 成员映射到类:
cmap = {
Entitites.TREE: (Tree, 100, (0, 0)),
Entitites.ROCK: (Rock, (0, 0)),
Entitites.FLOWER: (Flower, 'red', True, (0, 0)),
}
def my_func(entity):
t, *args = cmap[entity]
return t(*args)