python - 如何扩展 Enum 派生类的 Python 类属性

标签 python enums

from enum import Enum

class ErrorCode(str, Enum):
    GENERAL_ERROR = 'A general error has occurred.'
    INVALID_RECIPIENT_EMAIL_ADDRESS = 'The recipient email address provided is not a valid email address.'

    @classmethod
    def addErrorsAsAttrib(cls, err_code, err_description):
        setattr(cls, err_code, err_description)

extended_error_codes = ErrorCode.addErrorsAsAttrib('NEW_ERROR2', Enum('NEW_ERROR2', 'The new error 2'))

print(ErrorCode.__members__.keys())

# OUTPUT:
# dict_keys(['GENERAL_ERROR', 'INVALID_RECIPIENT_EMAIL_ADDRESS'])

我正在尝试找到一种方法来动态地将新的错误代码添加到我的 ErrorCode 类(枚举派生类)中,但无法确定执行此操作的正确方法。根据代码示例 - 我尝试了 setattr() 但这没有按预期执行。任何帮助将不胜感激。

最佳答案

Enum 被设计为不允许扩展。不过,根据您的用例,您有几个选择:

    class Country(JSONEnum):
        _init_ = 'abbr code country_name'  # remove if not using aenum
        _file = 'some_file.json'
        _name = 'alpha-2'
        _value = {
                1: ('alpha-2', None),
                2: ('country-code', lambda c: int(c)),
                3: ('name', None),
                }
    extend_enum(ErrorCode, 'NEW_ERROR2', 'The new error 2')

1 披露:我是 Python stdlib Enum 的作者,enum34 backport ,以及 Advanced Enumeration (aenum)图书馆。

关于python - 如何扩展 Enum 派生类的 Python 类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68524617/

相关文章:

c++ - C++ MFC 中未初始化枚举的值

c# - 如何转换 int 值以列出 Flag 枚举的 int 值

python - 如何将 View /模型中的任何方法作为 celery 任务

Python HTTP 服务器/客户端 : Remote end closed connection without response error

java - 枚举对象应该是无状态的吗?

c# - 为什么一个枚举可以有两个不同的名字和相同的数值?

typescript - 将枚举与其他类型的枚举进行比较

Python网络爬虫和 "getting"html源代码

python - 定义不同的 pandas xlsxwriter 边框类型

python - Nginx 和 uWSGI : Connection refused and 502 Bad Gateway error