【问题标题】:Unusual import of a class in Python在 Python 中异常导入一个类
【发布时间】:2023-02-17 16:13:16
【问题描述】:

kubernetes.client 文件夹中存在一个文件 exceptions.py,其中定义了 ApiException 类。所以我可以在我自己的文件中写入以下行,比如 myfile.py 并使用 ApiException 引发异常。

some_folder.myfile.py 代码 SN-P:

from kubernetes.client.exceptions import ApiException
.....
.....
    try:
        .....
    except ApiException as e:
        .....

没事儿。

同样在 rest.py 中存在于 kubernetes.client 文件夹中,正在导入相同的类 ApiException 并引发一些异常。

kubernetes.client.rest.py 代码 SN-P:

from kubernetes.client.exceptions import ApiException
.....
.....
     if not 200 <= r.status <= 299:
         raise ApiException(http_resp=r)

那也可以。但是我很困惑地看到下面的东西,因为ApiException是从some_file.py文件中的kubernetes.client.rest导入的(见下文),不是来自 kubernetes.client.exceptions,其中存在 ApiException 的实际类定义。

some_folder.some_file.py 代码 SN-P:

from kubernetes.client.rest import ApiException
.....
.....
    try:
       .....
    except ApiException as e:
       .....

上面的代码有效,但我真的很惊讶。有人可以向我解释这里发生了什么。对不起,我是 Python 新手。

笔记:

  1. ApiException类没有在kubernetes.client.rest中定义,它只在kubernetes.client.exceptions中定义
  2. 我在网上搜索了很多文章,但没有得到太多信息。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    名称ApiException 也在kubernetes.client.rest 中定义,因为它已从那里导入。 kubernetes.client.rest 正在使用它,所以它存在于那里。

    可以说该类应该从其导入典范它被定义的位置,但它不一定是。 some_folder.some_file.py 可能不知道异常最初是在哪里定义的,如果它只与 kubernetes.client.rest 交互并且只需要捕获在那里引发的异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-04
      • 2019-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2021-01-06
      • 2023-03-19
      相关资源
      最近更新 更多