[Tutor] working with new classes
Kent Johnson
kent37 at tds.net
Thu Mar 10 00:41:39 CET 2005
C Smith wrote:
> Alternatively, the list class can be appended with helpers like 'turn'
> and 'segment' which can actually turn the "ring" and remove a piece
> from it without worrying about the endpoint:
>
> ###
> >>> class ring(list):
> def turn(self, incr=1):
> incr%=len(self)
> self[:] = self[incr:]+self[:incr]
> def segment(self, i, length, incr=1):
> length=min(len(self),length)
> if i+length>len(self):
> return
> self[i::incr]+self[(length-i)%incr:i+length-len(self):incr]
>
> >>> l=ring(range(20)); l.turn(3); print l
> [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2]
> >>> >>> l.segment(17,5,3) #start at 17, length of 5, stride 3
> [0, 3]
> ###
This certainly looks like the simplest solution. You might want to look at UserList (in module
UserList in the standard library) which is a list work-alike implemented in Python. In the old days,
when it wasn't possible to subclass list, you would subclass UserList instead. Looking at the source
for UserList shows all the methods that have to change to make your ring class - it is a lot.
Kent
More information about the Tutor
mailing list