How to emulate matrix element access like 'a[i,j]'?

David Eppstein eppstein at ics.uci.edu
Sun Nov 24 22:51:59 EST 2002


In article <3DE19718.E31F0985 at irl.cri.nz>,
 Blair Hall <b.hall at irl.cri.nz> wrote:

> I have a class with a private matrix member (a Numeric.array)
> and I'd like to allow clients to access matrix members through
> suitable functions.
> 
> How can I create classes of object that supports the
> access style:
>     aMatrix[ row_index, col_index ]
> 
> It seems that __setitem__ and __getitem__ are not the right way to go.

Sure they are.  Just have them expect their argument to be a tuple of 
two integers.

E.g. you can do this with dictionaries:

>>> d={}
>>> d[2,5]=7
>>> d[2,5]
7
>>> d
{(2, 5): 7}

-- 
David Eppstein       UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list