如何使枚举指向类

2024-09-30 12:13:33 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个枚举来存储所有不同的实体类型

class Entities(Enum):
    TREE = auto()
    ROCK = auto()
    FLOWER = auto()

我想创建一个函数,它接受其中一个枚举(TREE,ROCK…),并且知道一个枚举对应于我拥有的一个类。 例如:

def myFunc(EntityType):
    return type(EntityType)

print(myFunc(Entities.ROCK))
>>>ROCK (where ROCK is an instance of the ROCK class)

如果有办法做到这一点,有没有办法,甚至可以初始化这个类 例如:

def myFunc(EntityType):
    myObj = EntityType(pos=(0,0))
    return myObj

Tags: 实体tree类型autoreturndefenummyfunc
3条回答

可以向Enum对象添加属性,也可以使用dict映射Enum。还有其他选择,但这些似乎最简单

假设您有TreeRockFlower等类,对应于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)

如果您只是抛弃auto并将类本身用作Entities的值,会怎么样?假设TreeRockFlower是类的名称:

class Entities(Enum):
    TREE = Tree
    ROCK = Rock
    FLOWER = Flower

这里Entities.TREE.valueTree的类构造函数

下面是Kyle Parsons回答的一个例子:

from enum import Enum
from dataclasses import dataclass

@dataclass
class Animal:
    name: str
    age: int
    type: str = None

@dataclass
class Cat(Animal):
    type: str = 'Cat'

@dataclass
class Dog(Animal):
    type: str = 'Dog'


class AnimalType(Enum):
    DOG = Dog
    CAT = Cat


def get_animal(type: Enum, name: str, age: int):
    return type.value(name, age)

print(get_animal(AnimalType.CAT, 'Peter', 12))

相关问题 更多 >

    热门问题