add 和 iadd 的区别? [英] Difference between add and iadd?

查看:143
本文介绍了add 和 iadd 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白 iadd、imul 等就地运算符的用途.

<块引用>

许多操作都有就地"版本.以下功能提供比通常更原始的就地运算符访问语法确实;例如,语句 x += y 等价于 x =operator.iadd(x, y).另一种表达方式是说 z =operator.iadd(x, y) 等价于复合语句 z = x;z+= y.

似乎我总是可以交替使用就地运算符或常规运算符.一个比另一个更好吗?

解决方案

无法使用 就地算法,而对于可变对象,它们可能是.一个简单的事实是不可变对象不会改变.

否则,在考虑可变对象时,使用就地"函数与不使用就地"函数会产生深远的影响.考虑以下几点:

<预><代码>>>>A = [1,2,3]>>>乙=甲>>>编号(A)4383125944>>>编号(B)4383125944>>>A = A + [1]>>>编号(A)4383126376>>>A += [1]>>>编号(A)4383126376

假设您正在编写一些代码,其中假定 B 是 A(可变对象)的软副本.通过在修改 A 时不使用就地"功能,可以悄悄地错过对 B 的所需修改.更糟糕的是,对代码的快速视觉检查使代码(例如,A = A + [2])看起来是正确实现的(也许在数学上是有意义的).如果真的只想修改一个对象而不接收新对象,那么就地"功能是正确的方法.

两者都不比另一个好.相反,在某些特定情况下,一种可能比另一种更受欢迎.

I'm not understanding the purpose of the in-place operators like iadd, imul, etc.

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.

It seems like I can always use either the in-place or regular operator interchangeably. Is one better than the other?

解决方案

The "in-place" functions for immutable objects cannot be implemented using an in-place algorithm, while for mutable objects they could be. The simple truth is that immutable objects don't change.

Otherwise, usage of "in-place" versus not "in-place" functions has deep ramifications when considering mutable objects. Consider the following:

>>> A = [1,2,3]
>>> B = A
>>> id(A)
4383125944
>>> id(B)
4383125944
>>> A = A + [1]
>>> id(A)
4383126376
>>> A += [1]
>>> id(A)
4383126376

Suppose you are writing some code where it is assumed that B is a soft copy of A (a mutable object). By not using the "in-place" function when modifying A, desired modifications to B can be quietly missed. What makes matters worse, is that quick visual inspection of the code makes it seem that the code (e.g., A = A + [2]) is implemented correctly (maybe it makes sense mathematically). If one really wants to just modify an object and not receive a new object, then the "in-place" function is the right way to go.

Neither is better than the other. Rather there are specific circumstances under which one might be preferred over the other.

这篇关于add 和 iadd 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆