在大多数情况下,该方法是基本的编译版本。当参数不是数组时,该函数使用该方法,但也具有某种备份。查看函数或方法的代码和/或文档会有所帮助。例如,如果在Ipython中请求查看sum方法的代码,我会看到它是编译代码。
In [711]: x.sum??
Type: builtin_function_or_method
String form: <built-in method sum of numpy.ndarray object at 0xac1bce0>
...
Refer to `numpy.sum` for full documentation.
如果我在np.sum
上做同样的操作,我会得到许多文档行以及一些Python代码:
if isinstance(a, _gentype):
res = _sum_(a)
if out is not None:
out[...] = res
return out
return res
elif type(a) is not mu.ndarray:
try:
sum = a.sum
except AttributeError:
return _methods._sum(a, axis=axis, dtype=dtype,
out=out, keepdims=keepdims)
return sum(axis=axis, dtype=dtype, out=out)
else:
return _methods._sum(a, axis=axis, dtype=dtype,
out=out, keepdims=keepdims)
如果我调用np.sum(x)
,其中x
是一个数组,它最终会调用x.sum()
:
sum = a.sum
return sum(axis=axis, dtype=dtype, out=out)
np.amax
和它类似但更简单。请注意,np.
形式可以处理不是数组(没有该方法)的对象,例如列表:np.amax([1,2,3])
。
np.dot
和x.dot
都显示为“内置”函数,因此我们无法关于优先级做出任何说明。它们可能最终都调用一些底层的C函数。
np.reshape
是另一个如果可能则委派的函数:
try:
reshape = a.reshape
except AttributeError:
return _wrapit(a, 'reshape', newshape, order=order)
return reshape(newshape, order=order)
所以,np.reshape(x,(2,3))
和 x.reshape((2,3))
的功能是完全相同的。但是,_wrapit
表达式可以使 np.reshape([1,2,3,4],(2,2))
。
np.sort
返回一个副本,通过对副本进行原地排序来实现:
a = asanyarray(a).copy()
a.sort(axis, kind, order)
return a
x.resize
是内置的,而np.resize
最终会执行np.concatenate
和reshape
。
如果你的数组是一个子类,例如矩阵或掩码,它可能有自己的变体。矩阵.sum
的操作是:
return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)