"from numpy import ndarray" 是如何工作的?

How does "from numpy import ndarray" work?

我查看了numpy, numpy/__init__.py, numpy/core/__init__.py的源代码和源代码树中的其他一些文件,但没有找到ndarray。他们使用什么技巧来启用命令

from numpy import ndarray

上班?

[当然,许多其他 Python 库也可以问同样的问题; numpyndarray 只是一个例子。我问是因为我想知道如何在我写的包中实现类似的效果]

这不是真正的“把戏”。您可以导入到 __init__.py 并通过包中的级别“提升”对象。

您要导入的来源是 here:

from .core import *

这使得 .core 中的任何对象都可以在包级别访问。他们再次使用相同的“技巧”here 从其中一个模块中拉出 ndarray,因此它被吊起多次,然后供 from .core import * 使用,然后第二次用于可作为 from numpy import ndarray.

我不是 numpy 专家,但我猜它是在 imported in numeric.py

from .multiarray import (
    [...]
    min_scalar_type, ndarray, nditer, nested_iters, promote_types,
    )

然后在 core/__init__.py:

from .numeric import *

顺便说一句,c 定义在 Cython 头文件中 numpy/__init__.pxd