What is this operator *= -1

后端 未结 2 1253
温柔的废话
温柔的废话 2020-12-11 04:34

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 av

2条回答
  •  时光说笑
    2020-12-11 05:28

    In the vast majority of the cases

    y *= 
    

    is the same as

    y = y * 
    

    but in the general case, it is interpreted as:

    y = imul(y, )
    

    which is then equivalent to:

    y = y.__imul__()
    

    if y's type overrides __imul__.

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


    EDIT

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

    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
    

提交回复
热议问题