更新时间:2022-04-16 10:03:10
首先,您需要了解 __add __
和 __ iadd __
。
对象的 __ add __
方法是常规添加:它接受两个参数,返回它们的总和,并且不修改任何参数。
An object's __add__
method is regular addition: it takes two parameters, returns their sum, and doesn't modify either parameter.
一个对象的 __iadd __
方法也需要两个参数,但是在原地进行更改,修改第一个参数的内容。因为这需要对象变异,所以不可变类型(如标准数字类型)不应该有 __ iadd __
方法。
An object's __iadd__
method also takes two parameters, but makes the change in-place, modifying the contents of the first parameter. Because this requires object mutation, immutable types (like the standard number types) shouldn't have an __iadd__
method.
a + b
使用 __ add __
。如果它存在, a + = b
使用 __ iadd __
如果没有,它通过 __ add __
来模拟它,如 tmp = a + b; a = tmp
。 operator.add
和 operator.iadd
以相同的方式不同。
a + b
uses __add__
. a += b
uses __iadd__
if it exists; if it doesn't, it emulates it via __add__
, as in tmp = a + b; a = tmp
. operator.add
and operator.iadd
differ in the same way.
另一个问题是: operator.iadd(x,y)
不等于 z = x; z + = y
,因为如果没有 __ iadd __
存在 __ add __
将被使用。您需要指定值以确保结果存储在两种情况下: x = operator.iadd(x,y)
。
To the other question: operator.iadd(x, y)
isn't equivalent to z = x; z += y
, because if no __iadd__
exists __add__
will be used instead. You need to assign the value to ensure that the result is stored in both cases: x = operator.iadd(x, y)
.
你可以很容易地看到它:
You can see this yourself easily enough:
import operator
a = 1
operator.iadd(a, 2)
# a is still 1, because ints don't have __iadd__; iadd returned 3
b = ['a']
operator.iadd(b, ['b'])
# lists do have __iadd__, so b is now ['a', 'b']