【问题标题】:Why some functions of itertools isn't accessible when import full module [duplicate]为什么导入完整模块时无法访问itertools的某些功能[重复]
【发布时间】:2019-07-05 12:27:00
【问题描述】:

我想使用 itertools 模块中的计数功能。当我尝试导入完整模块时

import itertools 

计数功能不可访问。只有当我像这样导入它时才能使用它

from itertools import count

如何在不一一导入的情况下导入完整的模块函数

【问题讨论】:

  • 在第一种情况下,您是尝试拨打count,还是拨打itertools.count?使用import X 语法时,您始终必须使用X. 限定模块中的名称。您可以使用 from itertools import * 避免命名空间限定,但 that's generally frowned on (命名空间是避免意外名称冲突的好东西,使用 from x import * 也可以防止静态分析器完成它们的工作)。
  • 我没有提到 itertools 就调用了 count。现在我明白我做错了什么。谢谢

标签: python python-3.x python-import


【解决方案1】:

如果您只需要count 功能,使用起来会更经济

from itertools import count

如果您需要整个模块,只需像这样导入它:

from itertools import *  # to be avoided due to potential name collusions

print(count(10))

或使用模块的全名导入所有内容:

import itertools

print(itertools.count(10))

或使用itertools的快捷方式:

import itertools as it

print(it.count(10))

【讨论】:

  • 谢谢,但是为什么当我通过 import itertools 导入模块时它没有导入所有功能?
  • 如果您只输入import itertools,则使用模块名称导入模块,并且可以通过itertools.count()访问其功能
  • 我编辑了答案以显示所有导入选项。
猜你喜欢
  • 2020-11-10
  • 2019-05-02
  • 2021-09-18
  • 1970-01-01
  • 2015-04-10
  • 2019-05-13
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
相关资源
最近更新 更多