首页 > 解决方案 > 我们如何通过扩展类在 Python 中结合抽象方法和自定义异常?

问题描述

有没有使用抽象方法的好方法?我担心人们仍然可以实例化 的对象class InvalidRequestError,但我没想到会发生这种情况?

情景 - 1

from http import HTTPStatus
from abc import ABC, abstractmethod

class BaseError(ABC, Exception): # Is it a good idea to subclass the Exception's class as well ?
    pass

class RequestError(BaseError, ABC):
    @abstractmethod
    def STATUS_CODE(self):
        raise NotImplementedError

class InvalidRequestError(RequestError):
    STATUS_CODE = HTTPStatus.BAD_REQUEST

# InvalidRequestError() # I was expecting it to raise an error but it didn't.

情景 - 2

from http import HTTPStatus
from abc import ABC, abstractmethod

class BaseError(ABC):
    pass

class RequestError(BaseError, ABC):
    @abstractmethod
    def STATUS_CODE(self):
        raise NotImplementedError

class InvalidRequestError(RequestError):
    STATUS_CODE = HTTPStatus.BAD_REQUEST
InvalidRequestError() # runs

但这正如我所期望的那样工作,(它引发了追溯)


import abc

class BaseError(abc.ABC):
    pass

class GeneralError(BaseError):

    @abc.abstractmethod
    def something(self):
        raise NotImplementedError

class Test(GeneralError):
    pass

# Test() # raises the exception I was looking for; TypeError: Can't instantiate abstract class Test with abstract methods...

# And so does the below,

from http import HTTPStatus
from abc import ABC, abstractmethod

class BaseError(ABC):
    pass

class RequestError(BaseError, ABC):
    @abstractmethod
    def STATUS_CODE(self):
        raise NotImplementedError

class InvalidRequestError(RequestError):
    pass # STATUS_CODE = HTTPStatus.BAD_REQUEST

# InvalidRequestError() # raises the exception I was looking for; TypeError: Can't instantiate abstract class Test with abstract methods.

在最后一个片段中,与最上面的片段相比,我所做的更改不再是子类化 Exceptions 类,而是将 STATUS_CODE 行替换为 pass。

我想了解为什么会发生这种情况以及实现此目的的更 Pythonic 方式是什么?

感谢路过;

标签: pythonexceptioninheritanceabc

解决方案


推荐阅读