uho*_*hoh 2 python numpy python-2.7
当我显示一个数组时,对象的默认__repr__()方法对于ndarray我想要做的来说太大了:
a = np.eye(32)
b = {'hello':42, 'array':a}
b
Run Code Online (Sandbox Code Playgroud)
产生:
{'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}
Run Code Online (Sandbox Code Playgroud)
我尝试了一个丑陋的解决方案,重新分配__repr__:
def wow():
return "wow!"
a.__repr__ = wow
Run Code Online (Sandbox Code Playgroud)
这会产生归因错误,我并不感到惊讶:
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
a.__repr__ = wow
AttributeError: 'numpy.ndarray' object attribute '__repr__' is read-only
Run Code Online (Sandbox Code Playgroud)
我可以用我想要的自定义代表创建一个类:
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
Run Code Online (Sandbox Code Playgroud)
现在产生:
32x32 float64
Run Code Online (Sandbox Code Playgroud)
但小问题是我现在必须在任何地方访问该属性。A.sum() 失败,Aasum() 有效。
有没有办法直接使用 NumPy 来做到这一点?
使用np.set_string_function:
>>> def __repr__(self):
... s0, s1 = self.shape
... dtp = self.dtype
... return '{}x{} {}'.format(s0, s1, dtp)
...
>>> np.set_string_function(__repr__)
>>> np.identity(5)
5x5 float64
Run Code Online (Sandbox Code Playgroud)
对于更高级的显示,您可能需要查看reprlib.
另一方面,如果您想要的只是让它更短一点,那np.set_printoptions可能是您最简单的选择。
如果您只需要将其应用于数组的子集,那么子类化可能确实是您的最佳选择。但是,我不确定 numpy.subclassing 的当前状态是什么。至少可以说,它曾经充满了微妙之处。
>>> class myarray(np.ndarray):
... def __repr__(self):
... return "wow!"
...
>>> np.identity(5).view(myarray)
wow!
Run Code Online (Sandbox Code Playgroud)