gpt4 book ai didi

python - 如果我将一个包导入到 python 中,我是否还必须单独强调它的模块?

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:52 25 4
gpt4 key购买 nike

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

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

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

为什么会这样?

最佳答案

import matplotlib as mpl

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

pyplotmatplotlib 包中的一个模块。如果需要从 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'>

关于python - 如果我将一个包导入到 python 中,我是否还必须单独强调它的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57371810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com