Python 就地运算符函数与标准运算符函数有何不同? [英] How are Python in-place operator functions different than the standard operator functions?
问题描述
来自文档:
许多操作都有一个就地"版本.以下功能提供更原始的访问就地操作员比平时语法确实;例如,语句 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.
问题:
为什么
operator.iadd(x, y)
不等于z = x;z += y
?
operator.iadd(x, y)
与 operator.add(x, y)
有何不同?
相关问题,但我对 Python 类方法不感兴趣;只是内置 Python 类型的常规运算符.
Related question, but I'm not interested in Python class methods; just regular operators on built-in Python types.
推荐答案
首先,你需要了解__add__
和__iadd__
的区别.
First, you need to understand the difference between __add__
and __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屋!