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

Carl Banks imbosol at vt.edu
Sun Nov 24 23:20:48 EST 2002


Blair Hall 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.


It certainly is.  When you write this:

    a[1,2]

Python interprets that as a[(1,2)]; that is, it creates a tuple and
passes that as the argument to __getitem__ and __setitem__.  So you
can define your class something like this:

    class allows_clients_to_access_matrix:
        ...

        def __getitem__(self,(row,column)):
            return self.private_matrix_member[row,column]

        def __setitem__(self,(row,column),value):
            self.private_matrix_member[row,colum] = value

The interesting thing is Python allows sequence unpacking into an
function argument.  This is an occasionally useful and not-well-known
trick.  However, that seems a little wasteful.  __getitem__ and
__setitem__ unpack a tuple just to pack it up again when subscripting
private_matrix_member.  Why not just pass the subscripts directly,
like this:

    class allows_clients_to_access_matrix:
        ...

        def __getitem__(self,subscripts):
            return self.private_matrix_member[subscripts]

        def __setitem__(self,subscripts,value):
            self.private_matrix_member[subscripts] = value

This is how I'd do it.


-- 
CARL BANKS



More information about the Python-list mailing list