首页 > 解决方案 > 如果我将一个包导入python,我是否还必须分别重要它的模块?

问题描述

很简单,我对编码相当陌生,我正在查看另一个人的代码以了解它在做什么,因为我必须将它用于数据分析,但我注意到他们做了以下事情:

 import matplotlib.pyplot as plt
.
.
.
import matplotlib as mpl
import numpy as np
.
.
import matplotlib.ticker

我认为“ import matplotlib as mpl”会导入 matplotlib 中包含的所有模块,因此需要ticker在此之后从 matplotlib 中单独导入模块“”?我会认为他们可以"mpl.ticker"稍后使用它会起作用吗?

为什么会这样?

标签: pythonpython-3.xmatplotlibimport

解决方案


import matplotlib as mpl

是的,这会从包中导入每个顶级函数和类matplotlib(并使它们在命名空间下可访问mpl),但它不会导入它拥有的任何子模块

pyplotmatplotlib包中的一个模块。如果需要从 访问类/函数pyplot,还必须导入:

import matplotlib.pyplot as plt

出于同样的原因,您必须import matplotlib.ticker能够使用该模块中的内容mpl.ticker.Foo

这是一个快速演示,显示仅导入基本matplotlib包是不够的:

>>> import matplotlib as mpl
>>> mpl.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'matplotlib' has no attribute 'pyplot'
>>> mpl.ticker
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'matplotlib' has no attribute 'ticker'
>>> import matplotlib.pyplot as plt
>>> plt.plot
<function plot at 0x0EF21198>
>>> import matplotlib.ticker
>>> mpl.ticker.Locator
<class 'matplotlib.ticker.Locator'>

推荐阅读