In python, how do I create two index slicing for m

2019-04-12 19:11发布

问题:

I am trying to write my own matrix class in python, just for testing purposes. In reality, this matrix class is in c++ and I am using SWIG to interface between the two. However, for this question, it might be simpler to consider a pure python implementation of this matrix class.

I want to be able to call this matrix class and use two-indexed slicing. For example, after we create 4x4 matrix of ones,

>>> A = Matrix(4,4,1)

I want to be able to get the sub 2x2 matrix:

>>>> A[1:2,1:2]

I've heard of the __getslice__ method, but this seems like it only allows single slicing, e.g. A[1:2]. So how can perform a two-index slicing so I can call A[i:j,l:k]?

Thanks!

回答1:

Note that __getslice__ is deprecated since version 2.0.

So consider the following minimal example:

class Foo:
    def __getitem__(self, *args):
        print args
f = Foo()
f[1:2,2:4]

This will print:

((slice(1, 2, None), slice(2, 4, None)),)

If you have a look at the data model docs, you'll see that slice objects are:

...used to represent slices when extended slice syntax is used. Special read-only attributes: start is the lower bound; stop is the upper bound; step is the step value; each is None if omitted. These attributes can have any type.

From here it should be pretty clear how to implement your 2 index slice handling.