假设我有这个枚举来存储所有不同的实体类型
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
可以向
Enum
对象添加属性,也可以使用dict
映射Enum
。还有其他选择,但这些似乎最简单假设您有
Tree
、Rock
、Flower
等类,对应于Enum
的值:我特别展示了一个扩展版本,其中每个类都有一个不同的初始值设定项和一组不同的默认值。如果它们都相同,请使用现有答案
选项1是这样定义枚举:
现在,
my_func
只是枚举本身的init
方法:第二个选项是将
Enum
成员映射到类:如果您只是抛弃
auto
并将类本身用作Entities
的值,会怎么样?假设Tree
、Rock
和Flower
是类的名称:这里
Entities.TREE.value
是Tree
的类构造函数下面是Kyle Parsons回答的一个例子:
相关问题 更多 >
编程相关推荐