[Tutor] subclass of list

Gregor Lingl glingl@aon.at
Sat Jan 4 02:36:09 2003


  :-( ! During preparing breakfast I suddenly recognized, that I had
written some nonsense here - (perhaps I should have breakfast
*before* writing emails.)

Gregor Lingl schrieb:

>
> Hi Bob!
> If you want to subclass a built-in type, you have to call the
> constructor of the parent-class in the same way as if you
> subclass any class. That means, as a "class"-method, which goes like 
> this:
>
> >>> class MyList(list):
> ...     def __init__(self, liste):
> ...         list.__init__(self,liste)
> ...
> >>> a = MyList([3,4])
> >>> a
> [3, 4]
> >>> a[0]
> 3


This is only necessary if you additionally do something else in
the constructor. Otherwise, the constructor of the parent-class is
called automatically.

So the following simple code also works:

 >>> class MyList(list):
...     pass
...
 >>> a = MyList([3,4])
 >>> a
[3, 4]
 >>> a[1]
4
 >>>

Of course, MyList here is nothing more than an ordinary list.
But also mlist doesn't need special initialization:

 >>> class mlist(list):
   def median(self):
       # according to Don Arnolds implementation
       tempList = self[:]
       tempList.sort()
       listLen = len(tempList)
       middleIndex = (listLen - 1) // 2
       if listLen % 2 == 1:
           #odd number of elements. return middle element
           return tempList[middleIndex]
       else:
           #even number of element. return average of middle 2 elements
           return (tempList[middleIndex] + tempList[middleIndex + 1]) / 2.0
 >>>
 >>> a = mlist([1,2,3])
 >>> a.median()
2
 >>> a = mlist([1,2,3,4])
 >>> a.median()
2.5

Sorry for this error!

As an - albeit rather useless ;-)  - example for a classe derived from 
list, which needs
the call of the constructor of the superclass ma serve the following:

 >>> class shortList(list):
...     def __init__(self, aList, maxlen=3):
...         self.maxlen = maxlen
...         list.__init__(self,aList[-maxlen:])
...     def append(self, element):
...         list.append(self,element)
...         if len(self)>3:
...             return self.pop(0)
...
 >>> a = shortList([2,3,5,7,11,13])
 >>> a
[7, 11, 13]
 >>> a.append(17)
7
 >>> a
[11, 13, 17]
 >>>

Here the definition of append (overwriting the orginal method) also shows,
how to call the append method of the superclass, which has to be done
exactly in the same way as it is done with __init__.

If you try to replace list.append(self,element) with self.append(element)
you will see immediatly that this is definitly another append (namely the
one, which is just going to be defined). Maybe this also will create
some insight on why some special syntax is necessary for calling
methods of the parent class.

Hope, this examples + explanations are correct now,

Gregor