首页 > 解决方案 > AttributeError 的起源:对象没有属性“cos”

问题描述

我遇到了这篇文章:Sympy to numpy 导致 AttributeError: 'Symbol' object has no attribute 'cos',并且想更多地了解异常的起源。

更准确地说,Eric 回答说:“当您调用 np.cos(a_symbol) 时会发生这种类型的错误,这显然会将 numpy 的底层转换为 a_symbol.cos()。” 我想了解这种行为的来源/来源: np.cos(x) 如何在幕后翻译成 x.cos() ?

我试图重现异常的引发,但无法追踪它的起源:

import numpy as np
class toto:
    def __init__(self,x):
        self.x = x
foo = toto(4)

class tata:
    def __init__(self,x):
        self.x = x

    def cos(self):
        print(self.x)

bar = tata(5)

try:
    np.cos(foo)
except:
    np.cos(bar)

这将打印 5。

干杯

标签: pythonnumpyattributeerror

解决方案


推荐阅读