使用乘法运算符 mul
例如,代码
import numpy as np
v = 1.0
a = float(v)
b = np.float64(v)
print(type(a*b), type(a.__mul__(b)))
a = complex(v)
b = np.complex128(v)
print(type(a*b), type(a.__mul__(b)))
产生以下输出<class 'numpy.float64'> <class 'float'>
<class 'numpy.complex128'> <class 'complex'>
自 <class 'float'>.__mul__(<class 'numpy.float64'>)
和 <class 'complex'>.__mul__(<class 'numpy.complex128'>)
实际上不返回 NotImplemented
,根据 Python documentation结果应该是 <class 'float'>
和 <class 'complex'>
, 分别。为什么不是这样?似乎内置数字类型的二元算术运算符(+、-、*、/等)的行为与其对应的
__op__()
有所不同职能?
最佳答案
关于 priority
我可能是错的.有一个优先级值控制如何ndarray
和它的子类交互,但是对于 Python 数字,它可能只是 NotImplemented
的问题。 ,或子类化
https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types
Note If the right operand’s type is a subclass of the left operand’s type
and that subclass provides a different implementation of the reflected
method for the operation, this method will be called before the left
operand’s non-reflected method. This behavior allows subclasses to
override their ancestors’ operations.
以你的例子:In [107]: a = 1.0; b = np.float64(1.0)
In [108]: type(a*b)
Out[108]: numpy.float64
In [109]: type(a.__mul__(b))
Out[109]: float
In [110]: type(b.__rmul__(a))
Out[110]: numpy.float64
In [111]: type(b).__mro__
Out[111]:
(numpy.float64,
numpy.floating,
numpy.inexact,
numpy.number,
numpy.generic,
float,
object)
b
控件 a*b
因为 type(b)
是 type(a)
的子类. b.__rmul__
用来。np.complex128
也是 complex
的子类.对于整数,
not implemented
是因素In [113]: c = 1; d = np.int64(1)
In [114]: type(c*d)
Out[114]: numpy.int64
In [115]: c.__mul__(d)
Out[115]: NotImplemented
In [116]: d.__rmul__(c)
Out[116]: 1
In [117]: type(_)
Out[117]: numpy.int64
In [118]: type(d).__mro__
Out[118]:
(numpy.int64,
numpy.signedinteger,
numpy.integer,
numpy.number,
numpy.generic,
object)
np.int64
不是 int
的子类.
关于python - 涉及 Python 内置数字类型和 Numpy 类型 float64 和 complex128 的二元算术运算结果的混淆类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68302275/