如何为 Enum 派生类扩展 Python 类属性

乔尔斯特
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 类(一个 Enum 派生类),但无法确定正确的方法来做到这一点。根据代码示例 - 我尝试过 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 stdlibEnumenum34backportAdvanced Enumeration ( aenum)库的作者。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章