gpt4 book ai didi

python - “异常”对象不可调用

转载 作者:行者123 更新时间:2023-12-05 08:51:55 25 4
gpt4 key购买 nike

我是 Python 的新手,我对某种异常方法的实现有疑问。这是代码(缩写):

class OurException(Exception):
"""User defined Exception"""
....

def get_single_value(command: str, connect_string: str, logger: Logger = None, custom_exception: Exception = OurException) -> Tuple[int, str]:
....
raise custom_exception("Errors in script\n\nexit .....")

我默认为OurException的异常参数不能这样抛出。但是,当我将最后一行中的 custom_exception 更改为 ExceptionOurException 时,问题就消失了。

在 OOP 上下文中,我会说,因为我已将参数定义为异常,并且可以通过这种方式调用异常,所以它可以保证工作。但是,我的 python 解释器和 IDE 不同意(Pycharm、Python 3.7)。

有些东西没有按照我认为的方式工作,我很感兴趣那是什么。

最佳答案

如果 custom_exception 应该是 Exception子类,您需要使用类型提示 Type[Exception],而不是 Exception 本身。否则,类型提示指定Exception实例 是预期的,并且通常Exception 的实例不是 可调用。

from typing import Type


def get_single_value(command: str,
connect_string: str,
logger: Logger = None,
custom_exception: Type[Exception] = OurException) -> Tuple[int, str]:
....
raise custom_exception("Errors in script\n\nexit .....")

关于python - “异常”对象不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58170051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com