我已经找到了numpy.ma.where()函数的源代码,但它似乎在调用numpy.where()函数,为了更好地理解它,如果可能的话,我想看看。
大多数 Python 函数是用 Python 语言编写的,但有些函数是用更原生的语言(通常是 C 语言)编写的。
您可以使用一些技巧来询问 Python 本身在何处定义了函数。可能是最便携的使用inspect模块:
>>> import numpy
>>> import inspect
>>> inspect.isbuiltin(numpy.ma.where)
False
>>> inspect.getsourcefile(numpy.ma.where)
'.../numpy/core/multiarray.py'
Run Code Online (Sandbox Code Playgroud)
但这不适用于本机(“内置”)函数:
>>> import numpy
>>> import inspect
>>> inspect.isbuiltin(numpy.where)
True
>>> inspect.getsourcefile(numpy.where)
TypeError: <built-in function where> is not a module, class, method, function, traceback, frame, or code object
Run Code Online (Sandbox Code Playgroud)
不幸的是,Python 不提供内置函数的源文件记录。您可以找出提供该功能的模块:
>>> import numpy as np
>>> np.where
<built-in function where>
>>> np.where.__module__
'numpy.core.multiarray'
Run Code Online (Sandbox Code Playgroud)
Python 不会帮助您找到该模块的本机 (C) 源代码,但在这种情况下,在 numpy 项目中查找具有相似名称的 C 源代码是合理的。我找到了以下文件:
numpy/core/src/multiarray/multiarraymodule.c
在该文件中,我找到了一个定义列表 ( PyMethodDef),包括:
{"where",
(PyCFunction)array_where,
METH_VARARGS, NULL},
Run Code Online (Sandbox Code Playgroud)
这表明 C 函数array_where是 Python 视为"where".
该array_where功能是在同一个文件中定义的,它主要是委托给PyArray_Where函数。
NumPy 的np.where函数是用 C 编写的,而不是 Python。一个不错的地方是PyArray_Where。
| 归档时间: |
|
| 查看次数: |
2653 次 |
| 最近记录: |