如果我将软件包导入python,是否还需要分别重视其模块? [英] If I import a package into python, do I also have to important it's modules separately?

查看:66
本文介绍了如果我将软件包导入python,是否还需要分别重视其模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单,我是编码的新手,我正在浏览另一个人的代码以了解它在做什么,因为我必须使用它进行数据分析,但我注意到他们这样做:

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

我认为" import matplotlib as mpl "将导入matplotlib中包含的所有模块,因此在此之后是否需要从matplotlib分别导入模块" ticker "?我本以为他们以后可以只使用"mpl.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? I would have thought that they could just use "mpl.ticker" later on and it would work?

为什么会这样?

推荐答案

import matplotlib as mpl

是的,这会从 matplotlib 包中导入每个顶级函数和类(并使其在名称空间 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.

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

pyplot is a module in the matplotlib package. If one needs access to classes/functions from pyplot, it has to imported also:

import matplotlib.pyplot as plt

出于相同的原因,您必须导入matplotlib.ticker 才能使用 mpl.ticker.Foo 中的模块中的内容.

For the same reason you have to import matplotlib.ticker to be able to use stuff from that module with mpl.ticker.Foo.

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

Here's a quick demo showing that just importing the base matplotlib package is not enough:

>>> 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,是否还需要分别重视其模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆