python导入只能以一种格式工作

时间:2014-02-24 16:16:30

标签: python python-import

当我建立时:

import matplotlib
pyplot.plot([1,2,3,4])
pyplot.ylabel('some numbers')
pyplot.show()

我明白了:

Traceback (most recent call last):
  File "/Users/Paulair/Desktop/mathGraphing.py", line 2, in <module>
    pyplot.plot([1,2,3,4])
NameError: name 'pyplot' is not defined
[Finished in 0.2s with exit code 1]

当我建立时:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

它有效。

2 个答案:

答案 0 :(得分:5)

在第一种情况下,您需要from matplotlib import pyplot

如果你只是import matplotlib,则必须使用matplotlib.pyplot.plot(....

抱歉,错误的答案是,pyplot是matplotlib的一个子模块,它故意不会通过简单的import matplotlibfrom matplotlib import *导入。见matplotlib has no attribute 'pyplot'。 你必须明确地导入它。

对于@Joe Kington的解释,分离的原因是:

  1. 允许在导入pyplot之前调用某些设置命令(例如matplotlib.use)和
  2. 允许使用matplotlib的其他部分而不会“重”导入完整的绘图功能。 (尽管如此,大部分都是#1。)

答案 1 :(得分:1)

这就是进口的运作方式。当您import module时,只导入名称 module。如果要在该模块中使用项目或子模块,则需要:

  1. 表示您使用的名称包含在某个模块中限定名称:module.submodule.function(...)
  2. 或导入所需子模块的名称,如果您愿意,可为其添加别名:import module.submoduleimport module.submodule as submodule
  3. 或首先导入您要使用的模块/功能/类名称:from module import submodulefrom module.submodule import function
  4. 否则,Python无法知道某个未定义名称可能实际存在的位置,因此它会引发NameError


    在您的特定情况下,您必须明确导入pyplot,因为matplotlib does not import该特定子模块本身(除其他good reasons之外,您可能会注意到import matplotlib.pyplot as plt需要一段时间才能执行:它是一个昂贵的导入,matplotlib选择避免默认执行它,因为核心功能不需要pyplot)。因此,您需要使用上面方法23的某些变体明确导入它。