比较时,为什么 try/except 块中引发的异常不等于方法中的 HTTPError?

Why is raised Exception in a try/except block not equal to HTTPError in a method when compared?

当我遇到或引发 HTTPError 异常并将异常作为 e 传递给方法时,传递给该方法的参数不等于 HTTPError。 (我理解 import * 不是最佳实践,但出于测试目的,它简化了事情。)

当我调试它并检查整个程序中异常的类型和相等性时,我得到以下信息:

e == HTTPError
False

error == HTTPError
False

type(error)
<class 'requests.exceptions.HTTPError'>

type(HTTPError)
<class 'type'>

代码:


from requests import *


def returnError(error : exceptions) -> dict:
    """ Returns an updated dictionary with corresponding message matching the error """
    if error == HTTPError:
            result = {}
    return result

try:
    raise HTTPError
except (HTTPError) as e:
    returnError(e)

这是因为 HTTPError 是一个 class 定义,但 e 实际上是 class 的一个实例。

类似的例子-

class Dog:
     def __init__(self):
         pass
type(Dog())
>> <class '__main__.Dog'>
type(Dog)
>> <class 'type'>

error == HTTPError 不起作用,因为您正在尝试将 class 与上述 class.

的实例进行比较

要检查 error 是否为 HTTPError,请执行 isinstance(error, HTTPError).