[Tutor] working with new classes

C Smith smichr at hotmail.com
Wed Mar 9 08:22:14 CET 2005


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 

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):
		head = self[:incr]
		self[:] = tail+head

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):

	def __getitem__(self, i):
		return self[(i-self._zero)%len(self)]

print l
print l    #same as original
print l[0] #crashes python


More information about the Tutor mailing list