我是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 .....")
Run Code Online (Sandbox Code Playgroud)
我默认设置为OurException的异常参数无法通过这种方式引发。但是,当我custom_exception将最后一行中的更改为Exception或时OurException,问题消失了。
在OOP上下文中,我想说的是,由于我已将参数定义为Exception,并且以这种方式可以调用Exception,因此可以保证它可以正常工作。但是,我的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 .....")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |