python - 我们如何通过扩展类在 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 方式是什么?
感谢路过;
解决方案
推荐阅读
- python - selenium.common.exceptions.WebDriverException:消息:无效参数:无法终止已退出的进程 OSX Catalina
- c# - 如何同时缩放和旋转图像?
- ssh - 如何通过嵌套的 tmux 会话正确设置远程服务器
- javascript - 角度反应形式patchValue或setValue不起作用 - Angular 10
- angular - 将 ng-template 注入组件
- c# - 不支持客户端 GroupBy - 修复
- php - 与我的 API 连接的 PHP If 和 Else 布尔值不起作用
- sql-server - 获取每个用户在 24 个时间段中的每小时通话数据
- security - Kubernetes EncryptionConfiguration 中的 `identity` 提供者提供什么样的安全性?
- javascript - 在谷歌应用脚本中不使用 document.getElementById() 获取文本输入框的值?