类的实例通过isinstance判断时却返回False
环境: python-3.6.5 djangorestframework-3.10.3 django-2.2.3
这是我自定义的一些异常:
继承关系是:WechatPaymentError -> BaseWechatError -> Exception
但是在统一处理异常时却出现了这样的情况:
通过type(exc)可以看到exc是WechatPaymentError的实例, 但是对WechatPaymentError和BaseWechatError的isinstance判断都是False
更新: 2020-07-31T14:37
找到了解决办法,但没明白具体原因.
上面这些自定义异常的路径是这样的utils.exception.WechatPaymentError, 其中utils目录已加入了sys.path里, pycharm也设置了"sources root".
在其他地方通过from exception import WechatPaymentError导入也是正常使用没有报错的.

现在解决办法是在使用异常的地方,将导入改为from utils.exception import WechatPaymentError, 这样在统一处理异常的地方isinstance(exc, WechatPayemntError就返回True了.
说明一下, 异常处理的代码和这些异常的定义写在同一个文件里(即utils.exception文件)
回答:
虽然你的异常定义在同一个文件,但是如果你以不同的路径导入,它就是不同的模块:
from exception import WechatPaymentErrorfrom utils.exception import WechatPaymentError
前者是模块 exception ,后者是模块 utils.exception 。
exception.WechatPaymentError 与 utils.exception.WechatPaymentError 也是不同的类。
如果在包里面导入,可以通过相对导入的方式(我猜你就是这个意思):
from .exception import WechatPaymentError如果当前包名是 utils ,那模块就是 utils.exception ,与通过 utils 绝对导入是一致的。
因此,关键在于搞清楚Python模块与包的组织方式以及 sys.path 的作用。
回答:
isinstance是会处理继承关系的,你应该是哪里写错了。。

以上是 类的实例通过isinstance判断时却返回False 的全部内容, 来源链接: utcz.com/a/36557.html

