【问题标题】:How can I decorate my enum when using FunctionalAPI?使用 FunctionalAPI 时如何装饰我的枚举?
【发布时间】:2021-12-29 07:01:43
【问题描述】:
from enum import IntEnum, unique

# @unique <- decorator syntax does not work for variable assignment
Weekday = IntEnum("Weekday", "sun mon tue wed thu fri sat", start=0)

显然可以将其写成一个类,但我想知道这是否可以使用如上所示的语法。

https://docs.python.org/3/library/enum.html#functional-api

【问题讨论】:

    标签: python enums decorator


    【解决方案1】:

    您可以将其用作函数而不是装饰器。

    Weekday = unique(IntEnum("Weekday", "sun mon tue wed thu fri sat", start=0))
    

    但是,这不是必需的:使用函数式 API 可以保证每个值都是唯一的。这是在_generate_next_value_ 中的enum.py 中完成的。

    创建IntEnum 调用__call__

    def __call__(cls, value, names=None, *, ..., start=1):
    

    调用cls._create_

    def _create_(cls, class_name, names, *, ..., start=1):
    

    在循环中调用_generate_next_value_以递增顺序分配值

    for count, name in enumerate(original_names):
        first_enum._generate_next_value_(name, start, count, last_values[:])
    

    【讨论】:

      猜你喜欢
      • 2022-11-28
      • 2023-03-30
      • 2010-11-12
      • 2012-07-28
      • 2020-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多