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

使用Python enum模块Functional API时如何给枚举添加装饰器?

实现方法

Python的装饰器本质是可调用对象的语法糖,@decorator挂载到类上的逻辑等价于类名 = decorator(类名),因此函数式API创建的枚举不需要依赖@语法,可以直接通过嵌套调用装饰器实现同等效果:

from enum import IntEnum, unique

# 直接把IntEnum返回的枚举类传入unique装饰器即可
Weekday = unique(IntEnum("Weekday", "sun mon tue wed thu fri sat", start=0))
  • 上述写法和显式定义类加@unique装饰器的运行效果完全一致,符合Python官方enum模块的函数式API使用规范
  • 如果需要挂载多个装饰器,按装饰器的执行顺序嵌套调用即可,例如需要依次应用decorator1、decorator2两个装饰器,写法为:
    Weekday = decorator1(decorator2(IntEnum("Weekday", "sun mon tue wed thu fri sat", start=0)))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:06:04