Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

python - Difference between add and iadd?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...