In python, how do I create two index slicing for my own matrix class?

安稳与你 提交于 2019-12-06 09:28:02

问题


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.



来源:https://stackoverflow.com/questions/23213057/in-python-how-do-i-create-two-index-slicing-for-my-own-matrix-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!