Hello,
After learning about the new class behavior, I am trying to implement a circular type list where, for example, you can compare the nth value to the "(n+1)th" value without worrying about going past the end of the list. (An old approach might be to create a function that converts a given index to the real index (e.g. maps the "(n+1)th" value back to the 1st value), but I thought I would try subclassing the list behavior.)
Seeing an ASPN entry on circular lists (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52246), I first tried to define a "turn" method for the list. The following works
###
class ring(list):
def turn(self, incr=1):
tail=self[incr:]
head = self[:incr]
self[:] = tail+headl=ring(range(10)) l.turn(5) #the list now has a turn method print l #--> [5, 6, 7, 8, 9, 0, 1, 2, 3, 4] ###
Then I tried to redefine how the list is initialized, desiring to give it a "zero" attribute which will be used whenever an item from the list is requested. I'm hoping not to have work with slices of the list--I just change how it is accessed. BUT...it doesn't work. Apparently __getitem__ is not accessed in order to print the list; and Python crashes when I try to print a single element.
Am I trying to subclass the wrong aspects of the list?
###
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 ###
/c
_______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
