Python, MetaClasses, HTTPException, __init_subclass__ - TypeError: exceptions must derive from BaseException

Python, MetaClasses, HTTPException, __init_subclass__ - TypeError: exceptions must derive from BaseException

有人能告诉我如何解决我的问题吗:

from werkzeug.exceptions import HTTPException

class HTTPExceptions(HTTPException):
    subclasses = dict()

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses[f'{cls.__name__}'] = cls.__name__


class Error501(HTTPExceptions):
    code = 501

当我尝试 运行:

raise HTTPExceptions.subclasses['Error501']

我得到了

TypeError: exceptions must derive from BaseException

有人知道怎么解决吗?

cls.__name__ 是一个字符串,因此您定义 HTTPExceptions.subclasses 的方式就像是字符串到字符串的映射。我假设您的意图是:

cls.subclasses[f'{cls.__name__}'] = cls

当 运行 导致

Traceback (most recent call last):
  File "D:/Dev/python/scratch/subclass_exception.py", line 13, in <module>
    raise HTTPExceptions.subclasses['Error501']
__main__.Error501