当我展示一个数组时,ndarray
对象的默认__repr__()
方法对于我的需求来说太过冗长:
a = np.eye(32)
b = {'hello':42, 'array':a}
b
生成:
{'array': array([[ 1., 0., 0., ..., 0., 0., 0.],
[ 0., 1., 0., ..., 0., 0., 0.],
[ 0., 0., 1., ..., 0., 0., 0.],
...,
[ 0., 0., 0., ..., 1., 0., 0.],
[ 0., 0., 0., ..., 0., 1., 0.],
[ 0., 0., 0., ..., 0., 0., 1.]]), 'hello': 42}
我尝试了一个丑陋的解决方案,重新分配
__repr__
:def wow():
return "wow!"
a.__repr__ = wow
这导致了一种归因错误,我并不感到惊讶:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.__repr__ = wow
AttributeError: 'numpy.ndarray' object attribute '__repr__' is read-only
我可以创建一个包含自定义repr的类,这正是我想要的:
class NP(object):
def __init__(self, a):
self.a = a
def __repr__(self):
s0, s1 = self.a.shape
dtp = self.a.dtype
return '{}x{} {}'.format(s0, s1, dtp)
A = NP(a)
A
现在会产生以下结果:
32x32 float64
但是问题在于现在我需要到处访问该属性。A.sum() 会失败,A.a.sum() 可以正常工作。
是否有一种直接使用 NumPy 解决这个问题的方法?
ndarray
的子类,而不是组合。 - timgeb