<p>我不是类方面的专家,但是使用<a href="https://docs.scipy.org/doc/numpy/user/basics.subclassing.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy/user/basics.subclassing.html</a>中的代码:</p>
<pre><code>import numpy as np
class FooArray(np.ndarray):
def __new__(subtype, shape, dtype=float, buffer=None, offset=0,
strides=None, order=None, foo='Foo'):
# Create the ndarray instance of our type, given the usual
# ndarray input arguments. This will call the standard
# ndarray constructor, but return an object of our type.
# It also triggers a call to InfoArray.__array_finalize__
obj = super(FooArray, subtype).__new__(subtype, shape, dtype,
buffer, offset, strides,
order)
# set the new 'info' attribute to the value passed
obj.foo = foo
# Finally, we must return the newly created object:
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.foo = getattr(obj, 'foo', None)
arr = np.arange(9).reshape(3,3)
fa = arr.view(FooArray)
print(fa.sum())
</code></pre>
<p>编辑:在进一步查看上面提到的页面并播放更多内容之后,我想到了:</p>
^{pr2}$
<p>编辑2:修正数组finalize的最后一行</strong></p>