python - What is this operator *= -1 -


i'm going through python activities , given example code operator: y *= -1

i had through relevant python docs, no avail.

i know y += 1, example, short y = y + 1. y = y * -1 y equals y times -1 maybe?

closest thing in python docs find this: x * y: product of x , y

is it?

in vast majority of cases

y *= <expr> 

is same

y = y * <expr> 

but in general case, interpreted as:

y = imul(y, <expr>) 

which equivalent to:

y = y.__imul__(<expr>) 

if y's type overrides __imul__.

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


edit

it might not clear why assignment needed, i.e. why intrepreted y = imul(y, <expr>), , not imul(y, <expr>).

the reason makes lot of sense following 2 scenarios give same result:

c = * b 

and

c = c *= b 

now, of course works if a , b of same type (e.g. floats, numpy arrays, etc.), if aren't, possible result of operation have type of b, in case operation cannot inplace operation of a, result needs assigned a, in order achieve correct behavior.

for example, works, assignment:

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

whereas if assignment dropped, a remains unchanged:

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

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -