【发布时间】:2022-01-16 01:15:04
【问题描述】:
PEP 3141 为不同类型的数字引入了抽象基类,以允许自定义实现。
我想从numbers.Real 派生一个类并计算它的正弦值。使用 pythons math-module,这工作正常。当我在 numpy 中尝试相同的操作时,出现错误。
from numbers import Real
import numpy as np
import math
class Mynum(Real):
def __float__(self):
return 0.0
# Many other definitions
a = Mynum()
print("math:")
print(math.sin(a))
print("numpy:")
print(np.sin(a))
结果
math: 0.0 numpy: AttributeError: 'Mynum' object has no attribute 'sin' The above exception was the direct cause of the following exception: Traceback (most recent call last): [...] in <module> print(np.sin(a)) TypeError: loop of ufunc does not support argument 0 of type Mynum which has no callable sin method
似乎 numpy 试图调用其参数的 sin-method。对我来说,这很令人困惑,因为标准数据类型(如 float)也没有这样的方法,但 np.sin 可以处理它们。
是否只是对标准数据类型进行某种硬编码检查,不支持 PEP 3141?还是我在课堂上错过了什么?
因为实现所有必需的方法非常繁琐,所以这是我当前与math-module 一起使用的代码:
from numbers import Real
import numpy as np
import math
class Mynum(Real):
def __init__(self):
pass
def __abs__(self):
pass
def __add__(self):
pass
def __ceil__(self):
pass
def __eq__(self):
pass
def __float__(self):
return 0.0
def __floor__(self):
pass
def __floordiv__(self):
pass
def __le__(self):
pass
def __lt__(self):
pass
def __mod__(self):
pass
def __mul__(self):
pass
def __neg__(self):
pass
def __pos__(self):
pass
def __pow__(self):
pass
def __radd__(self):
pass
def __rfloordiv__(self):
pass
def __rmod__(self):
pass
def __rmul__(self):
pass
def __round__(self):
pass
def __rpow__(self):
pass
def __rtruediv__(self):
pass
def __truediv__(self):
pass
def __trunc__(self):
pass
a = Mynum()
print("math:")
print(math.sin(a))
print("numpy:")
print(np.sin(a))
【问题讨论】:
-
该 PEP 不适用于
numoy'sdtypes。
标签: python python-3.x numpy types numpy-ufunc