我遵循了this guide的实现对象,这些对象可以通过np.ndarray
,+
,-
等二进制运算符与*
进行交互...
根据我的情况的建议,我设置了__array_ufunc__ = None
,并实现了__mul__
和__div__
之类的二进制操作。但是,在这些示例中,__mul__
有效,而__div__
无效。
这是MWE:
import numpy as np
class ArrayLike(object):
__array_ufunc__ = None
def __mul__(self, other):
return 'mul'
def __div__(self, other):
return 'div'
array = np.arange(3)
npnum = np.float32(2.0)
alike = ArrayLike()
alike * array # 'mul'
alike / array # '*** TypeError: operand 'ArrayLike' does not support ufuncs (__array_ufunc__=None)'
alike * npnum # 'mul'
alike / npnum # '*** TypeError: operand 'ArrayLike' does not support ufuncs (__array_ufunc__=None)'
答案 0 :(得分:0)
欢迎堆栈溢出!
import numpy as np
class ArrayLike(object):
__array_ufunc__ = None
def __mul__(self, other):
return 'mul'
def __truediv__(self, other):
return 'div'
array = np.arange(3)
npnum = np.float32(2.0)
alike = ArrayLike()
alike / npnum # 'div'
请注意,我使用的是__truediv__
而不是__div__
。 __div__
对Python 3无效,对Python 2无效。
有关更多信息,请参阅Python 3 Operators
如果这回答了您的问题,请确保将其标记为答案。谢谢!