我有一个类试图在其对象上调用 add 函数。 请考虑以下代码:
class Test(object):
data = "hello"
def __getattr__(self, name):
print('getattr: ' + name)
return getattr(self.data, name)
>>> obj = Test()
>>> obj + 'world'
TypeError: unsupported operand type(s) for +: 'Test' and 'str'
>>> type(obj).__add__(obj, 'world')
AttributeError: type object 'Test' has no attribute '__add__'
在新款式中,
(obj + "world")
相当于
type(obj).__add__(obj,"world")
那么为什么我在这两种情况下都会遇到不同的错误? 我期待同样的错误,因为两个陈述看起来都等于我。我几周前开始使用python。因此,我无法找到我在这里缺少的概念。
答案 0 :(得分:2)
+
运算符并不完全等同于type(obj).__add__
。如果未定义其他方法,+
也会调用type(other).__radd__
,并且当两种方法都不存在时,会引发更多描述性错误。如果您想要将+
完全模拟为函数,请使用operator.add
。