Python 就地运算符函数与标准运算符函数有何不同?
来自文档:
许多操作都有“就地” 版本。以下功能 提供更原始的访问 比平常更到位的操作员 语法确实如此;例如, 语句 x += y 等价于 x = 运算符.iadd(x, y)。另一种方式 就是说 z = operator.iadd(x, y) 相当于 复合语句 z = x; z += y。
问题:
为什么
operator.iadd(x, y)
不等于z = x; z += y
?operator.iadd(x, y)
与operator.add(x, y)
有何不同?
相关问题,但我对Python类方法不感兴趣;只是内置 Python 类型的常规运算符。
From the docs:
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.
Questions:
Why isn't
operator.iadd(x, y)
equivalent toz = x; z += y
?How does
operator.iadd(x, y)
differ fromoperator.add(x, y)
?
Related question, but I'm not interested in Python class methods; just regular operators on built-in Python types.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您需要了解
__add__
和__iadd__
之间的区别。对象的
__add__
方法是常规加法:它接受两个参数,返回它们的总和,并且不修改任何一个参数。对象的 __iadd__ 方法也采用两个参数,但会就地进行更改,修改第一个参数的内容。因为这需要对象突变,所以不可变类型(如标准数字类型)不应具有
__iadd__
方法。a + b
使用__add__
。a += b
使用__iadd__
(如果存在);如果没有,它会通过 __add__ 来模拟它,如 tmp = a + b; 所示。 a = tmp。operator.add
和operator.iadd
的不同之处相同。对于另一个问题:operator.iadd(x, y) 不等于 z = x; z += y,因为如果不存在
__iadd__
,则将使用__add__
代替。您需要分配该值以确保在两种情况下都存储结果:x = operator.iadd(x, y)
。你自己很容易就能看到这一点:
First, you need to understand the difference between
__add__
and__iadd__
.An object's
__add__
method is regular addition: it takes two parameters, returns their sum, and doesn't modify either parameter.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
uses__add__
.a += b
uses__iadd__
if it exists; if it doesn't, it emulates it via__add__
, as intmp = a + b; a = tmp
.operator.add
andoperator.iadd
differ in the same way.To the other question:
operator.iadd(x, y)
isn't equivalent toz = 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:
也许是因为某些 Python 对象是不可变的。
我猜
operator.iadd(x, y)
相当于z = x; z += y
仅适用于字典和列表等可变类型,但不适用于数字和字符串等不可变类型。Perhaps because some Python objects are immutable.
I'm guessing
operator.iadd(x, y)
is equivalent toz = x; z += y
only for mutable types like dictionaries and lists, but not for immutable types like numbers and strings.