Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy认可的特殊方法文件的位置_Python_Numpy - Fatal编程技术网

Python numpy认可的特殊方法文件的位置

Python numpy认可的特殊方法文件的位置,python,numpy,Python,Numpy,math.exp和numpy.exp之间的区别之一是,如果您有一个自定义类C具有C.exp方法,numpy.exp将注意并委托给此方法,而math.exp将不会: class C: def exp(self): return 'hey!' import math math.exp(C()) # raises TypeError import numpy numpy.exp(C()) # evaluates to 'hey!' 然而,如果你去看电影,这似乎是理所当然

math.exp
numpy.exp
之间的区别之一是,如果您有一个自定义类
C
具有
C.exp
方法,
numpy.exp
将注意并委托给此方法,而
math.exp
将不会:

class C:
    def exp(self):
        return 'hey!'

import math
math.exp(C())  # raises TypeError
import numpy
numpy.exp(C())  # evaluates to 'hey!'
然而,如果你去看电影,这似乎是理所当然的。在任何地方都没有明确说明。是否有记录此功能的地方


更一般地说,有没有一个地方有numpy识别的所有此类方法的列表?

这不是
np.exp
函数的特殊行为;这只是计算对象数据类型数组的结果

np.exp
与许多numpy函数一样,在执行操作之前,会尝试将非数组输入转换为数组

In [227]: class C:
     ...:     def exp(self):
     ...:         return 'hey!'
     ...:     
In [228]: np.exp(C())
Out[228]: 'hey!'

In [229]: np.array(C())
Out[229]: array(<__main__.C object at 0x7feb7154fa58>, dtype=object)
In [230]: np.exp(np.array(C()))
Out[230]: 'hey!'
np.exp
可以处理数组对象数据类型,前提是所有元素都有
exp
方法。整数不会<代码>ndarray也没有

In [233]: np.exp([C(),C(),np.array(2)])
AttributeError: 'numpy.ndarray' object has no attribute 'exp'
math.exp
需要一个数字、一个Python标量(或者可以转换成标量的东西,例如
np.array(3)

我希望这种行为在所有
ufunc
中都是常见的。我不知道其他不遵循该协议的numpy函数

在某些情况下,
ufunc
将委托给
\uuu
方法:

In [242]: class C:
     ...:     def exp(self):
     ...:         return 'hey!'
     ...:     def __abs__(self):
     ...:         return 'HEY'
     ...:     def __add__(self, other):
     ...:         return 'heyhey'
     ...:     
In [243]: 
In [243]: np.abs(C())
Out[243]: 'HEY'
In [244]: np.add(C(),C())
Out[244]: 'heyhey'
In [242]: class C:
     ...:     def exp(self):
     ...:         return 'hey!'
     ...:     def __abs__(self):
     ...:         return 'HEY'
     ...:     def __add__(self, other):
     ...:         return 'heyhey'
     ...:     
In [243]: 
In [243]: np.abs(C())
Out[243]: 'HEY'
In [244]: np.add(C(),C())
Out[244]: 'heyhey'