Python-ese for indexing a list within a class

Greg Landrum glandrum at my-deja.com
Wed Jul 19 21:19:23 EDT 2000


In article <8l4v6k$rd4$1 at news.rchland.ibm.com>,
  "Larry Whitley" <ldw at us.ibm.com> wrote:
> Is the following the appropriate Python-ese for indexing a list
within a
> class?
>
> # the following is defined outside of either class or function
> nCounters = 4
> a,b,c,d = range(nCounters)
>
> # now define the class
> class C:
>     def __init__(self):
>         cnt = [0] * nCounters
>     def someFunction(self):
>         # some code
>         self.cnt[a] = self.cnt[a] + 1 # <<< here's the statement in
question
>         # some more code
>
> I'm trying to avoid the considerably ugly:
>
> self.cnt[self.a] = self.cnt[self.a] + 1
>
> The code seems to work ok but is this the right/best/prettiest/(etc)
way to
> go about it?
>

How about something like this:
class C:
    def __init__(self,nCounters):
        self.cnt = [0] * nCounters
    def __getitem__(self,which):
        return self.cnt[which]
    def __setitem__(self,which,val):
        self.cnt[which] = val

This would then be used like:

foo = C(4)
print foo.cnt
foo[1] = foo[1] + 1
print foo.cnt

If you want to get a bit fancier, you could even do:

class C2:
    def __init__(self,nCounters):
        self.cnt = [0] * nCounters
    def __getitem__(self,which):
        return self.cnt[which]
    def __setitem__(self,which,val):
        self.cnt[which] = val
    def __len__(self):
        return len(self.cnt)
    def __getslice__(self,start,stop):
        return self.cnt[start:stop]

And use it like this:

foo = C2(4)
print foo[:]
foo[1] = foo[1] + 1
print foo[:]

I hope this helps,
-greg



Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list