gpt4 book ai didi

Python 奇怪错误 : "TypeError: ' NoneType' object is not callable"

转载 作者:太空狗 更新时间:2023-10-29 20:52:42 24 4
gpt4 key购买 nike

我正在实现一个简单的类来表示二维向量。以下是相关部分:

class Vector:
def __init__( self, x, y ):
self.vec_repr = x, y

def __add__( self, other ):
new_x = self.x + other.x
new_y = self.y + other.y
return Vector( new_x, new_y )

def __getattr__( self, name ):
if name == "x":
return self.vec_repr[0]
elif name == "y":
return self.vec_repr[1]

稍后,我有类似的东西:

a = Vector( 1, 1 )
b = Vector( 2, 2 )
a + b

我收到 TypeError: 'NoneType' object is not callable。这特别奇怪,因为错误没有被标记为在任何特定的行上,所以我不知道去哪里找!

很奇怪,于是做了一些实验,发现它出现在a+b这一行。另外,当我按如下方式重新上课时:

class Vector:
def __init__( self, x, y ):
self.x, self.y = x, y

def __add__( self, other ):
new_x = self.x + other.x
new_y = self.y + other.y
return Vector( new_x, new_y )

错误消失了!

我看到有很多关于与此类似的错误的问题 - 所有问题似乎都涉及某个函数名称在某处被变量覆盖,但我看不出这是在哪里发生的!

作为另一个线索,当我将 __getattr__() 的默认返回类型更改为其他类型时 - 例如 str - 错误会变成 TypeError: 'str' object is not callable

关于发生了什么的任何想法? __getattr__() 有什么我不明白的行为吗?

最佳答案

问题是您的 __getattr__ 不会为 xy 以外的属性返回任何内容,也不会引发 AttributeError。因此,当查找 __add__ 方法时,__getattr__ 返回 None 并因此返回错误。

您可以通过使 __getattr__ 返回其他属性的值来解决此问题。事实上,您必须确保 __getattr__ 从其父类(super class)中为所有未处理的属性调用该方法。但实际上 __getattr__ 在这里使用是错误的。它应该谨慎使用,并且在没有更明显、更高级别的解决方案可用时使用。例如,__getattr__ 对于动态调度是必不可少的。但在您的情况下,xy 值在代码运行之前是众所周知且定义明确的。

正确的解决方案是创建 xy 属性,并且根本不实现 __getattr__

@property
def x(self):
return self.vec_repr[0]

@property
def y(self):
return self.vec_repr[1]

关于Python 奇怪错误 : "TypeError: ' NoneType' object is not callable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6891477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com