You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Enum枚举成员指向对应类并支持类初始化操作

实现方案

你可以直接将枚举成员的值绑定为对应的自定义类,再通过重写枚举的__call__方法实现直接调用枚举成员生成实例的效果,完整实现步骤如下:

1. 先定义对应的自定义实体类

# 示例自定义实体类,可根据需求扩展属性和方法
class Tree:
    def __init__(self, pos):
        self.pos = pos
    def __repr__(self):
        return "TREE"

class Rock:
    def __init__(self, pos):
        self.pos = pos
    def __repr__(self):
        return "ROCK"

class Flower:
    def __init__(self, pos):
        self.pos = pos
    def __repr__(self):
        return "FLOWER"

2. 改造枚举类,绑定实体类

把枚举成员的取值直接设置为对应的实体类,同时重写__call__方法支持直接初始化:

from enum import Enum

class Entities(Enum):
    # 成员值绑定对应的自定义类
    TREE = Tree
    ROCK = Rock
    FLOWER = Flower

    # 重写调用方法,直接初始化绑定的类
    def __call__(self, *args, **kwargs):
        return self.value(*args, **kwargs)

3. 效果测试

需求1:获取枚举对应的自定义类

def get_entity_class(entity_type: Entities):
    return entity_type.value

print(get_entity_class(Entities.ROCK))
# 输出:<class '__main__.Rock'>

需求2:通过枚举直接初始化类实例

完全符合你给出的写法:

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

print(myFunc(Entities.ROCK))
# 输出:ROCK (对应Rock类的实例)

内容的提问来源于stack exchange,提问作者Gote

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 13:45:05