python - 涉及 Python 内置数字类型和 Numpy 类型 float64 和 complex128 的二元算术运算结果的混淆类型

标签 python numpy

使用乘法运算符 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/

相关文章:

python - 在Django Restframework中使用elasticsearch的最佳方法是什么

python - np.searchsorted() 背后有一个有趣的算法吗?

python - Pandas 有条件地创建数据框列 : based on multiple conditions

python - 在 numpy 中应用二维函数的最佳方法

python - numpy.array bool 值与 int 的混合

python - 在顺序读取的多个特征文件上训练 Keras 模型以节省内存

python - 使用傻瓜盒对 CNN 进行攻击的代码,出了什么问题?

python - pandas 中高效的列内操作

python - 从具有大量值的数据框中快速创建数组?

python - IsADirectoryError : [Errno 21] Is a directory: '/home/cali/Dropbox/'