问题
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? I would have thought that they could just use "mpl.ticker"
later on and it would work?
Why would this be the case?
回答1:
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.
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
For the same reason you have to import matplotlib.ticker
to be able to use stuff from that module with mpl.ticker.Foo
.
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'>
来源:https://stackoverflow.com/questions/57371810/if-i-import-a-package-into-python-do-i-also-have-to-important-its-modules-sepa