如果我将一个包导入到python中,我是否也必须对它进行重要处理';是分开的模块吗?

如果我将一个包导入到python中,我是否也必须对它进行重要处理';是分开的模块吗?,python,python-3.x,matplotlib,import,Python,Python 3.x,Matplotlib,Import,很简单,我对编码相当陌生,我正在浏览另一个人的代码以了解它在做什么,因为我必须使用它进行数据分析,但我注意到他们做了以下工作: import matplotlib.pyplot as plt . . . import matplotlib as mpl import numpy as np . . import matplotlib.ticker 我认为“将matplotlib导入为mpl”将导入matplotlib中包含的所有模块,因此在此之后需要从matplotlib单独导入模块“tic

很简单,我对编码相当陌生,我正在浏览另一个人的代码以了解它在做什么,因为我必须使用它进行数据分析,但我注意到他们做了以下工作:

 import matplotlib.pyplot as plt
.
.
.
import matplotlib as mpl
import numpy as np
.
.
import matplotlib.ticker
我认为“
将matplotlib导入为mpl
”将导入matplotlib中包含的所有模块,因此在此之后需要从matplotlib单独导入模块“
ticker
?我原以为他们以后可以使用
“mpl.ticker”
,这样就行了

为什么会这样

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

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

import matplotlib.pyplot as plt
出于同样的原因,您必须
导入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'>
>将matplotlib作为mpl导入
>>>mpl.pyplot
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:模块“matplotlib”没有属性“pyplot”
>>>mpl.ticker
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:模块“matplotlib”没有属性“ticker”
>>>将matplotlib.pyplot作为plt导入
>>>plt.plot
>>>导入matplotlib.ticker
>>>mpl.ticker.Locator

是否可以像导入mpl.pyplot作为plt一样导入?你的回答很好,但你遗漏了问题的一部分:“我们以后可以使用”mpl.ticker“吗?”如果你想在
pyplot
中访问
plt.plot([1,2,3]),
mpl.pyplot.plot([1,2,3])
将工作吗?@Astariul
将mpl.pyplot作为plt导入将不工作,导入时不能对包使用别名。