How do numpy's in-place operations (e.g. `+=`) work?

前端 未结 4 1607
一向
一向 2020-12-01 14:47

The basic question is: What happens under the hood when doing: a[i] += b?

Given the following:

import numpy as np
a = np.arange(4)
i = a         


        
4条回答
  •  执笔经年
    2020-12-01 15:29

    The first thing you need to realise is that a += x doesn't map exactly to a.__iadd__(x), instead it maps to a = a.__iadd__(x). Notice that the documentation specifically says that in-place operators return their result, and this doesn't have to be self (although in practice, it usually is). This means a[i] += x trivially maps to:

    a.__setitem__(i, a.__getitem__(i).__iadd__(x))
    

    So, the addition technically happens in-place, but only on a temporary object. There is still potentially one less temporary object created than if it called __add__, though.

提交回复
热议问题