Python就地操作符函数如何与标准操作符函数不同? [英] How are Python in-place operator functions different than the standard operator functions?
问题描述
为什么不是 operator.iadd(x,y)
等于 z = x; z + = y
? operator.add(x,y)
?
Why isn't operator.iadd(x, y)
equivalent to z = x; z += y
? And how does operator.iadd(x, y)
differ from operator.add(x, y)
?
从 docs :
From the docs:
许多操作都有一个in放置
版本。以下函数
提供了比原来的
语法更原始的对
就地操作符的访问;例如,
语句x + = y等价于x =
operator.iadd(x,y)。
的另一种解释是,z =
operator.iadd(x,y)相当于
复合语句z = x; z + = y。
Many operations have an "in-place" version. The following functions provide a more primitive access to in-place operators than the usual syntax does; for example, the statement x += y is equivalent to x = operator.iadd(x, y). Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y.
相关问题,但我对Python类方法不感兴趣;只是对内置Python类型的常规操作符而已。
Related question, but I am not interested in Python class methods; just regular operators on built-in Python types.
推荐答案
首先,您需要了解 __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']
这篇关于Python就地操作符函数如何与标准操作符函数不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!