Style guide for subclassing built-in types?

Michael Spencer mahs at telcopartners.com
Wed Feb 23 13:21:27 EST 2005


janeaustine50 at hotmail.com wrote:
> Kent Johnson wrote:
> 
>>janeaustine50 at hotmail.com wrote:
>>
>>>p.s. the reason I'm not sticking to reversed or even reverse :
> 
> suppose
> 
>>>the size of the list is huge.
>>
>>reversed() returns an iterator so list size shouldn't be an issue.
>>
>>What problem are you actually trying to solve?
>>
>>Kent
>>
> 
> 
> Oh, you are right.
> 
> Actually, it's more complicated than simple reversion. The list order
> should be somewhat "twisted" and the list is big.
> 
> For example,
> 
> [1,2,3,4,5,6,7,8,9,10]
> 
> --> [10,9,8,7,6,1,2,3,4,5]
> 
> so __getitem__(self,i) => __getitem__(self,-i-1) if i<len(size)/2,
> otherwise __getitem__(self,i-len(size)/2)
> 
> I'd like to have TwistedList class that takes in an original list and
> pretends as if it is twisted actually. However, I have to have
> duplicate codes here and there to make it act like a "list", say assert
> twisted_list == [10,9,...] and for each in twisted_list and etc.
> 
If you want a twisted 'view' of an existing list, then a wrapper makes most sense.

If, however, you only need the twisted version, why not simply override 
list.__init__ (and extend, append etc... as required):

  >>> class rev_list(list):
  ... 	def __init__(self, iterable):
  ... 		list.__init__(self, iterable[::-1])
  ... 	
  >>> l = rev_list([1,2,3])
  >>> l
  [3, 2, 1]

Michael




More information about the Python-list mailing list