Skip to main content
 首页 » 编程设计

python之dtype float 'object' 和 'float' 上算术的不同行为

2025年01月19日11wuhuacong

大家好,我只是 Python 的菜鸟(即使是编程方面),所以我的问题听起来可能很基础,但我很难理解这一点。

为什么“ float 对象”上的算术选择行为?

import numpy as np 
 
a = np.random.normal(size=10) 
a = np.abs(a) 
b = np.array(a, dtype=object) 
 
np.square(a) # this works 
np.square(b) # this works 
 
np.sqrt(a) # this works 
np.sqrt(b) # AttributeError: 'float' object has no attribute 'sqrt' 

图片链接是我在本地jupyter notebook中的运行结果:

jupyter notebook运行结果

欣赏有用的见解!谢谢


编辑 050418 09:53 -- 添加一个我认为是类似问题的链接 Numpy AttributeError: 'float' object has no attribute 'exp'

请您参考如下方法:

@Warren 指出 square“代表”乘法。我通过制作一个包含列表的对象数组来验证这一点:

In [524]: arr = np.array([np.arange(3), 3, [3,4]]) 
In [525]: np.square(arr) 
TypeError: can't multiply sequence by non-int of type 'list' 

square 适用于数组的其余部分:

In [526]: np.square(arr[:2]) 
Out[526]: array([array([0, 1, 4]), 9], dtype=object) 

sqrt 不适用于以下任何一项:

In [527]: np.sqrt(arr) 
--------------------------------------------------------------------------- 
AttributeError                            Traceback (most recent call last) 
<ipython-input-527-b58949107b3d> in <module>() 
----> 1 np.sqrt(arr) 
 
AttributeError: 'numpy.ndarray' object has no attribute 'sqrt' 

我可以让 sqrt 使用自定义类:

class Foo(float): 
    def sqrt(self): 
        return self**0.5 
 
In [539]: arr = np.array([Foo(3), Foo(2)], object) 
In [540]: np.square(arr) 
Out[540]: array([9.0, 4.0], dtype=object) 
In [541]: np.sqrt(arr) 
Out[541]: array([1.7320508075688772, 1.4142135623730951], dtype=object)