python - 如果我将一个包导入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"
稍后使用它会起作用吗?
为什么会这样?
解决方案
import matplotlib as mpl
是的,这会从包中导入每个顶级函数和类matplotlib
(并使它们在命名空间下可访问mpl
),但它不会导入它拥有的任何子模块。
pyplot
是matplotlib
包中的一个模块。如果需要从 访问类/函数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'>
推荐阅读
- kubernetes - 在 Minikube 启动时运行命令
- javascript - 如何通过单击按钮从本地存储中删除元素?
- css - Angular Datatable - 覆盖按钮 CSS
- ios - Apache2 服务器视频流与移动设备和 PC 的兼容性
- javascript - 在传单上覆盖 div 并停止鼠标动作传播
- javascript - JavaScript。forEach 返回一个未定义的
- autodesk-forge - Autodesk forge:主页和信息图标消失了
- java - 如何从 Java 调用 Perl 6?
- css - 不遵守 Outlook 2013 表格边框
- javascript - axios获取请求中的意外令牌