Nonclassical when changing cloning behavior

Along with the book, I was provided with the Python program I am digging into now.

The program uses a global data structure with the name globdat, in a specific procedure, the numpy array inside is globdatassigned to a local variable:

a = globdat.array

Then, in the next while loop, the variable is aupdated every iteration according to:

a[:] += da[:]

The result of this operation is an update globdat.array, which is used in subsequent operations.

Is use required here [:], or is it just used to indicate that it is also cloned into globdat.array? Can anyone clarify this coding style?

+4
source share
3 answers

The second [:], on the right side, is redundant. It simply copies dabefore using it in concatenation, which is pointless.

Left:

a[:] += da

First, let's understand what it does a += da. It displays:

a = a.__iadd__(da)

The call __iadd__extends the original list aand returns self, that is, a link to the list. Thus, the assignment that occurs after this has no effect in this case (same as a=a).

This achieves the original goal, i.e. to expand the global array.


Now what does a[:] += da? It displays:

a[:] = a[:].__iadd__(da)

Or more tiring:

a.__setitem__(slice(None), a.__getitem__(slice(None)).__iadd__(da))

For readability, write it as (not valid python syntax):

a.__setitem__(:, a.__getitem__(:).__iadd__(da))

So a[:].__iadd__(da):

  • creates a copy a(call a2)
  • da a2
  • return a2

a[:] = ...:

  1. a a2 .

, , , - .


.

+4

:

a[:] += da[:]

:

a.__setitem__(slice(None),
              a.__getitem__(slice(None)).__iadd__(da.__getitem__(slice(None))))

.

, a da , extend():

a.extend(da)
+4

, , .

a[:] = da[:]

, , += , .

.

+4

All Articles