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

Python中可以将类或方法作为Enum枚举类的取值使用吗?

解决方案

报错原因

  • 当你把类赋值给Enum的成员时,直接访问TestEnum.a_name拿到的是TestEnum枚举类型的实例对象,而非你存入的A类本身,枚举实例默认不可调用,因此触发该类型错误。
  • 枚举类型存储的原始值需要通过.value属性获取。

修复代码

from enum import Enum


class A:
    def __init__(self, b):
        self.b = b


class TestEnum(Enum):
    a_name = A


# 调用.value属性拿到实际存储的类对象
a_class = TestEnum.a_name.value

a_instance = a_class(b=1)

print(type(a_instance))
# 运行输出:<class '__main__.A'>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:24:04