我有一个来自 numpy.ndarray 的子类,它修改了按索引获取项目的行为。但是,当有人在我的子类上打印时,我想保留原始的 ndarray 输出格式。我尝试覆盖 __iter__ 函数,但似乎不起作用。鉴于 __getitem__ 已重载,是否可以按底层数组顺序打印输出数字?
import numpy as np
class imarray(np.ndarray):
def __new__(cls, d, f):
nd = np.asarray(d)
return super(imarray, cls).__new__(cls,(nd.size,), dtype=nd.dtype, buffer=nd).view(imarray)
def __init__(self, d, f):
self.f = f
def __array_finalize__(self, o):
pass
def __getitem__(self, i):
return super(imarray, self).__getitem__(self.f(i))
def __setitem__(self, i, y):
return super(imarray, self).__setitem__(self.f(i), y)
def __iter__(self):
return super(imarray, self).__iter__
if __name__ == "__main__":
a = imarray([1., 2., 3.1415], lambda i:i+1)
print a[0] # print .2
a[-1] =.4
print a[-1] # print .4
print a # print [ 2. 3.1415 0.4 ] but want [ 0.4 2. 3.1415 ]