简体   繁体   English

如果我只是从numpy模块引用它,为什么我必须从numpy导入它

[英]Why do I have to import this from numpy if I am just referencing it from the numpy module

Aloha! 阿罗哈!

I have two blocks of code, one that will work and one that will not. 我有两个代码块,一个可以工作,另一个不会。 The only difference is a commented line of code for a numpy module I don't use. 唯一的区别是我不使用的numpy模块的注释代码行。 Why am I required to import that model when I never reference "npm"? 当我从不引用“npm”时,为什么我需要导入该模型?

This command works: 此命令有效:

import numpy as np
import numpy.matlib as npm

V  = np.array([[1,2,3],[4,5,6],[7,8,9]])
P1 = np.matlib.identity(V.shape[1], dtype=int)
P1

This command doesn't work: 此命令不起作用:

import numpy as np
#import numpy.matlib as npm

V  = np.array([[1,2,3],[4,5,6],[7,8,9]])
P1 = np.matlib.identity(V.shape[1], dtype=int)
P1

The above gets this error: 上面得到了这个错误:

AttributeError: 'module' object has no attribute 'matlib'

Thanks in advance! 提前致谢!

Short Answer 简答

This is because numpy.matlib is an optional sub-package of numpy that must be imported separately. 这是因为numpy.matlibnumpy的可选子包,必须单独导入。

The reason for this feature may be: 此功能的原因可能是:

  • In particular for numpy , the numpy.matlib sub-module redefines numpy 's functions to return matrices instead of ndarrays, an optional feature that many may not want 特别是对于numpynumpy.matlib子模块重新定义numpy的函数来返回矩阵而不是ndarrays,这是一个许多人可能不想要的可选功能
  • More generally, to load the parent module without loading a potentially slow-to-load module which many users may not often need 更一般地,加载父模块而不加载许多用户可能不经常需要的可能很慢的加载模块
  • Possibly, namespace separation 可能是命名空间分离

When you import just numpy without the sub-package matlib , then Python will be looking for .matlib as an attribute of the numpy package. 当你导入numpy而没有子包matlib ,Python会寻找.matlib作为numpy包的一个属性。 This attribute has not been assigned to numpy without importing numpy.matlib (see discussion below) 如果没有导入numpy.matlib该属性尚未分配给numpy (请参阅下面的讨论)

Sub-Modules and Binding 子模块和绑定

If you're wondering why np.matlib.identity works without having to use the keyword npm , that's because when you import the sub-module matlib , the parent module numpy (named np in your case) will be given an attribute matlib which is bound to the sub-module. 如果你想知道为什么np.matlib.identity工作而不必使用关键字npm ,那是因为当你导入子模块matlib ,父模块numpy (在你的情况下命名为np )将被赋予一个属性matlib ,这是绑定到子模块。 This only works if you first define numpy . 这只适用于您首先定义numpy

From the reference : 来自参考

When a submodule is loaded using any mechanism (eg importlib APIs, the import or import-from statements, or built-in import ()) a binding is placed in the parent module's namespace to the submodule object. 当使用任何机制(例如,importlib API,import或import-from语句或内置import ())加载子模块时,绑定将放置在父模块的命名空间中,并附加到子模块对象。

Importing and __init__.py 导入和__init__.py

The choice of what to import is determined in the modules' respective __init__.py files in the module directory. 要导入的内容的选择取决于模块目录中模块各自的__init__.py文件。 You can use the dir() function to see what names the respective modules define. 您可以使用dir()函数查看相应模块定义的名称。

>> import numpy

>> 'matlib' in dir(numpy)
# False

>> import numpy.matlib

>> 'matlib' in dir(numpy)
# True

Alternatively, if you look directly at the __init__.py file for numpy you'll see there's no import for matlib . 或者,如果您直接查看__init__.py文件以获取numpy您将看到matlib没有导入。

Namespace across Sub-Modules 子模块之间的命名空间

If you're wondering how the namespace is copied over smoothly ; 如果你想知道命名空间是如何顺利复制的;

The matlib source code runs this command to copy over the numpy namespace: matlib源代码运行此命令以复制numpy命名空间:

import numpy as np                                    # (1)
...
# need * as we're copying the numpy namespace
from numpy import *                                   # (2)
...
__all__ = np.__all__[:] # copy numpy namespace        # (3)

Line (2), from numpy import * is particularly important. 第(2)行, from numpy import *尤为重要。 Because of this, you'll notice that if you just import numpy.matlib you can still use all of numpy modules without having to import numpy ! 因此,您会注意到如果您只是导入numpy.matlib您仍然可以使用所有numpy模块而无需导入numpy

Without line (2), the namespace copy in line (3) would only be attached to the sub-module. 如果没有第(2)行,第(3)行中的命名空间副本只会附加到子模块。 Interestingly, you can still do a funny command like this because of line (3). 有趣的是,由于第(3)行,你仍然可以做这样一个有趣的命令。

import numpy.matlib               
numpy.matlib.np.matlib.np.array([1,1])

This is because the np.__all__ is attached to the np of numpy.matlib (which was imported via line (1)). 这是因为np.__all__附着到npnumpy.matlib (其经管线(1)导入)。

You never use npm but you do use np.matlib , so you could change your 2nd import line to just: 你从不使用npm但你确实使用了np.matlib ,所以你可以将你的第二个导入行改为:

import numpy.matlib

Or you could keep your 2nd import line as is but instead use: 或者您可以按原样保留第二个导入行,而是使用:

P1 = npm.identity(V.shape[1], dtype=int)

Is there are reason you don't use np.identity ? 你有没有理由不使用np.identity

P1 = np.identity(V.shape[1], dtype=int)

This module contains all functions in the numpy namespace, with the following replacement functions that return matrices instead of ndarrays. 该模块包含numpy命名空间中的所有函数,具有以下替换函数,这些函数返回矩阵而不是ndarrays。

Unless you are wedded to 2d np.matrix subclass, you are better off sticking with the regular ndarray versions. 除非你坚持使用2d np.matrix子类,否则你最好坚持使用常规的ndarray版本。

(Others have pointed out that the import why is based on the __init__ specs for numpy . numpy imports most, but not all of its submodules. The ones it does not automatically import are used less often. It's a polite way of saying, You don't really need this module ) (其他人已经指出,导入为什么是基于numpy__init__规范numpy导入大部分,但不是所有子模块。它不自动导入的子模块使用次数较少。这是一种礼貌的说法, You don't really need this module

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我必须使用python中的电子邮件模块“从模块导入”? - Why do I have to “from module import” with the email module in python? 我正在尝试导入numpy以在Python脚本中使用,但出现错误“没有名为numpy的模块” - I am trying to import numpy for use in a Python script but I get the error “No module named numpy” 为什么我需要从 tkinter 模块显式导入字体模块,即使使用“*”导入了完整模块? - Why do I need to explicitly import the font module from the tkinter module even if have imported the full module using “*”? 当我只是“导入 numpy”时出现 Python 导入错误 - Python import error when I just 'import numpy' NumPy:我可以创建一个仅包含 dict 数组中的值的数组吗? - NumPy: Can I create an array of just the values from an array of dicts? 为什么我没有看到Numpy的DeprecationWarning? - Why am I not seeing Numpy's DeprecationWarning? 我尝试将浮点数从元组分配给 numpy 数组 - I am try to assigne float numbers from tuple to numpy array 如何将不同类型的数据从文件导入Python Numpy数组? - How do I import data with different types from file into a Python Numpy array? 从numpy import导入numpy作为np - import numpy as np versus from numpy import 无法导入我刚刚在 VS 代码中安装的模块(我使用的是 Ubuntu) - unable to import the module that i have just installed in VS code(i am using Ubuntu)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM