[英]operator expression vs direct call to built-in method in new style python class
I have a class which tries to call add function on its object. 我有一个试图在其对象上调用add函数的类。 Consider the following code : 考虑以下代码:
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__'
In new style classes, 在新样式类中,
(obj + "world")
is equivalent to 相当于
type(obj).__add__(obj,"world")
So why am I getting different error in both these cases? 那么为什么在这两种情况下我都会得到不同的错误? I was expecting same error as both statements appear equal to me. 我期待着相同的错误,因为两个语句看起来都和我一样。 I've started python few weeks ago. 我几周前开始使用python。 Therefore, I am unable to find which concept I am missing here. 因此,我找不到在这里缺少的概念。
The +
operator is not entirely equivalent to type(obj).__add__
. +
运算符并不完全等同于type(obj).__add__
。 +
also calls type(other).__radd__
if the other method is not defined, and throws more descriptive errors when neither method exists. 如果未定义其他方法, +
也将调用type(other).__radd__
,并且当这两种方法都不存在时会引发更多描述性错误。 If you want to exactly emulate +
as a function, use operator.add
. 如果您想将+
准确地模拟为函数,请使用operator.add
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.