Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - What is this operator *= -1

I'm going through some Python activities and was given example code with this operator: y *= -1

I had a look through the relevant Python docs, to no avail.

I know y += 1, for example, is short for y = y + 1. So is this y = y * -1 y equals y times -1 maybe?

Closest thing in Python docs I could find is this: x * y: product of x and y

Is this it?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In the vast majority of the cases

y *= <expr>

is the same as

y = y * <expr>

but in the general case, it is interpreted as:

y = imul(y, <expr>)

which is then equivalent to:

y = y.__imul__(<expr>)

if y's type overrides __imul__.

This means that if y's type overrides the inplace multiplication operator, y*=<expr> is performed inplace, while y=y*<expr> is not.


EDIT

It might not be immediately clear why the assignment is needed, i.e. why it is intrepreted as y = imul(y, <expr>), and not just imul(y, <expr>).

The reason is that it makes a lot of sense for the following two scenarios to give the same result:

c = a * b

and

c = a
c *= b

Now, this of course works if a and b are of the same type (e.g. floats, numpy arrays, etc.), but if they aren't, it is possible for the result of the operation to have the type of b, in which case the operation cannot be an inplace operation of a, thus the result needs to be assigned to a, in order to achieve the correct behavior.

For example, this works, thanks to the assignment:

from numpy import arange
a = 2
a *= arange(3)
a
=> array([0, 2, 4])

Whereas if the assignment is dropped, a remains unchanged:

a = 2
imul(a, arange(3))
=> array([0, 2, 4])
a
=> 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...