[英]If I import a package into python, do I also have to important it's modules separately?
Very simply, I'm reasonably new to coding, and I'm going through another person's code to understand what it is doing as I have to use it for data analysis but I notice that they do the following:很简单,我对编码相当陌生,我正在浏览另一个人的代码以了解它在做什么,因为我必须使用它进行数据分析,但我注意到他们执行以下操作:
import matplotlib.pyplot as plt
.
.
.
import matplotlib as mpl
import numpy as np
.
.
import matplotlib.ticker
I thought that " import matplotlib as mpl
" would import all modules contained in matplotlib and therefore there need to separately import the module " ticker
" from matplotlib after this?我认为“ import matplotlib as mpl
”会导入matplotlib中包含的所有模块,因此在此之后需要从matplotlib单独导入模块“ ticker
”? I would have thought that they could just use "mpl.ticker"
later on and it would work?我原以为他们可以稍后使用"mpl.ticker"
,它会起作用吗?
Why would this be the case?为什么会这样?
import matplotlib as mpl
Yes, this imports every top level function and class from the matplotlib
package (and makes them accessible under the namespace mpl
), but it does not import any submodules it has .是的,这会从matplotlib
包中导入每个顶级函数和类(并使它们可以在命名空间mpl
下访问),但它不会导入它拥有的任何子模块。
pyplot
is a module in the matplotlib
package. pyplot
是matplotlib
包中的一个模块。 If one needs access to classes/functions from pyplot
, it has to imported also:如果需要从pyplot
访问类/函数,它还必须导入:
import matplotlib.pyplot as plt
For the same reason you have to import matplotlib.ticker
to be able to use stuff from that module with mpl.ticker.Foo
.出于同样的原因,您必须import matplotlib.ticker
才能通过mpl.ticker.Foo
使用该模块中的mpl.ticker.Foo
。
Here's a quick demo showing that just importing the base matplotlib
package is not enough:这是一个快速演示,显示仅导入基本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'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.