<p>这很难。我能想到的只有2个解决方案,而且我不喜欢其中任何一个——一个来自numpy文档中关于ndarray的子类化——使用array_wrap。其次是更多的保存->;<strong>覆盖</strong>np.总和以及你想要的其他功能。在</p>
<p><strong>注意:</strong></p>
<p>下面的代码<strong>需要抛光</strong>,主要是使用<strong>array_wrap的解决方案</strong>。不过,看起来<strong>array_wrap</strong>是正确的方向,因为它也适用于其他函数(*.mean()等),但正如您所说,文档非常密集,很难说黑客攻击这些神奇函数会产生什么后果。
重写在另一方面是简单明了的,但是谁想重写所有现有的函数呢?在</p>
<pre><code>import numpy as np
class MyArray(np.ndarray):
def __new__(cls, input_array, foo='foo'):
self = input_array.view(cls)
self.foo = foo
return self
# First solution - define this func that is magically called on results (check documentation)
def __array_wrap__(self, out_arr, context=None):
if not out_arr.shape:
out_arr = out_arr.reshape(-1)[0]
# Check more on documentation. This is just example
# It definitely needs more polishing
return out_arr
else:
# This part was there before. That means it needs to be used, but thats up to you. It seems it simply passes result to __array_finalize__
return super(MyArray, self).__array_wrap__(out_arr,self, context)
def __array_finalize__(self, from_array):
if from_array is not None:
self.foo = getattr(from_array, 'foo', 'foo')
# Use only if you know what you are doing
## This is second solution. Override. Check result, act accordingly
#def sum(self,*args,**kwargs):
# result = super().sum()
# if not result.shape:
# return result.reshape(-1)[0]
# else:
# return result
a = MyArray(np.arange(9).reshape(3,3))
print(a.foo)
print(a.sum())
print(a.mean().__class__)
print(a.sum().__class__)
print(np.mean(a).__class__)
>>> foo
>>> 36
>>> <class 'numpy.float64'>
>>> <class 'numpy.int64'>
>>> <class 'numpy.float64'>
</code></pre>