[Tutor] working with new classes

Sean Perry shaleh at speakeasy.net
Wed Mar 9 09:55:22 CET 2005


C Smith wrote:
> ###
> class Ring(list):
>     def __init__(self, l):
>         self[:] = l
>         self._zero = 0
>        
>     def turn(self, incr=1):
>         self._zero+=incr
> 
>     def __getitem__(self, i):
>         return self[(i-self._zero)%len(self)]
> 
> l=Ring(range(10))
> print l
> l.turn(5)
> print l    #same as original
> print l[0] #crashes python
> ###
> 

This is a classic mistake. l[0] --> l.__getitem__(l, 0), which you 
understand. However in __getitem__ you then call self[] which will just 
call __getitem__ again. and again. and again. ....

The way out is to explicitly call the parent's __getitem__.

def __getitem__(self, i):
     # list is out parent, call its method
     return list.__getitem__(self, (i - self._zero) % len(self))


More information about the Tutor mailing list