【问题标题】:Why do I need to "from tqdm import tqdm" instead of just "import tqdm"?为什么我需要“从 tqdm 导入 tqdm”而不仅仅是“导入 tqdm”?
【发布时间】:2021-03-21 07:52:17
【问题描述】:

可能是一个简单的问题,但我刚刚开始使用 Python,并尝试了解库的工作原理。

所以我的问题是为什么我需要输入

from tqdm import tqdm

而不仅仅是

import tqdm

喜欢其他库吗?

我知道当您只需要库的一部分时,您可以这样做。但在这种情况下,如果我不这样做,我的程序将无法运行。第二个表达式不应该包含所有内容吗? 如果我用它运行我的程序,我会收到错误:

"TypeError: 'module' 对象不可调用"

【问题讨论】:

  • 这样你每次只需要输入tqdm() 而不是tqdm.tqdm()
  • 不必。当您执行from some_module import some_name 时,您将导入整个模块,并将some_name 分配给该范围内的some_name。如果您使用import tqdm,您可以使用tqdm.tqdm,它恰好使用与模块相同的名称。事实上,import tqdm 通常是首选
  • 现在,some_name 本身可能是另一个模块,但不一定是。在tqdm.tqdm 的情况下,它不是。这是相关的documentation btw

标签: python python-import libraries python-module tqdm


【解决方案1】:

from tqdm import tqdm 表示你在 tqdm 下导入模块 tqdm。

import tqdm 表示导入整个包。在这种情况下,您必须使用tqdm.tqdm(),这相当于在上述情况下仅使用tqdm()

【讨论】:

  • 不,这并不意味着在这种情况下。有一个模块,tqdm,其中有一个名称,tqdm
【解决方案2】:

第一个tqdm 是包或模块的名称。第二个tqdm 是在该包/模块下定义的可调用对象。它可能是一个不同的可调用对象,例如 trange:

from tqdm import trange

您所做的基本上是在 tqdm 模块中导入可调用的 tqdm。

【讨论】:

  • 不,它与import tqdm.tqdm as tqdm不等效。没有名为tqdm.tqdm的模块
  • 感谢指正。我和另一个图书馆混在一起了。
【解决方案3】:

tqdm 里面有一个名为tqdm 的模块。现在到你的tqdm你可以

  1. 导入包tqdm中的所有模块并使用名为tqdm的模块:
import tqdm

for i in tqdm.tqdm(range(10)):
  pass

  1. 只需通过以下方式导入tqdm 包的tqdm 模块:
from tqdm import tqdm
for i in tqdm(range(10)):
  pass

【讨论】:

  • 没有模块tqdm.tqdm
  • 啊,谢谢!我只是感到困惑,因为它具有相同的名称,不知道这是可能的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-25
相关资源
最近更新 更多