0

In numpy, it's possible to take slice and modify it:

a = np.array([1, 2, 3, 4, 5])
a[2:4] = [7, 8]
# now a is np.array([1, 2, 7, 8, 5])

How is it implemented?

Suppose you have some 2d array class, Array2d which has some tricky implementation of 2d array, like 2-dimensional trie. And you want the __getitem__ method to return Array2dSlice object, which can be modified:

a = Array2d()
...
#     [1  2  3]
# a = [4  5  6]
#     [7  8  9]

a[1:3, 1:3] = [[0, 0], [0, 0]]
#     [1  2  3]
# a = [4  0  0]
#     [7  0  0]

If there was operator overloading in Python, I would use it in Array2dSlice class. But there is no operator overloading. Is there a decent replacement for it?

DLunin
  • 1,050
  • 10
  • 20
  • possible duplicate of [How to override the slice functionality of list in its derived class](http://stackoverflow.com/questions/16033017/how-to-override-the-slice-functionality-of-list-in-its-derived-class) – will Aug 20 '14 at 15:04

1 Answers1

3

Where the indexing operator [] appears on the left hand side of the assignment operator =, the special method called is __setitem__, not __getitem__.

In this case, the effective call is:

a.__setitem__(tuple(slice(1, 3), slice(1, 3)), [[0, 0], [0, 0]])

This provides all the information you need in one place to efficiently modify the array.

ecatmur
  • 152,476
  • 27
  • 293
  • 366