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)
显然,人们可以将其写为一个类,但我想知道使用上面所示的语法是否可以实现这一点。
最佳答案
您可以将其用作函数而不是装饰器。
Weekday = unique(IntEnum("Weekday", "sun mon tue wed thu fri sat", start=0))
但是,这不是必需的:使用功能 API 可以保证每个值都是唯一的。这是在 enum.py 中的 _generate_next_value_
中完成的.
创建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[:])
关于python - 使用FunctionalAPI 时如何装饰我的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70018999/