设置现有 numpy 对象的__hash__



在我的实验中,我有一个 numpy 对象的实例,我需要设置其__hash__方法。

我尝试了各种方法(实际上似乎完全相同(:

import numpy as np
x = np.array([1, 2, 3])
x.flags.writeable = False  # set the array immutable
setattr(x, '__hash__', lambda self: 0)  # doesn't work without self either
AttributeError: 'numpy.ndarray' object attribute '__hash__' is read-only
x.__hash__ = lambda self: 0
AttributeError: 'numpy.ndarray' object attribute '__hash__' is read-only

有什么方法可以强制对象接受我的实现吗?这实际上是一个更广泛的问题:有没有办法将任何属性/方法分配给现有对象(包括魔术方法等(?

创建一个继承 np 的对象类?然后编写__hash__函数 我有点菜鸟,但认为这会起作用吗?


class Test(np):
def __hash__(self):
# function