[Tutor] Little subclass understanding problem
Michael H. Goldwasser
goldwamh at slu.edu
Thu Nov 15 20:05:36 CET 2007
On Thursday November 15, 2007, Tom wrote:
> I am trying to understand what happens in the following scenario:
>
> class Sub_class(Base_class):
> def __init__(self, data):
> Base_class.__init__(self, data)
>
> as in:
>
> # snippet from http://viner.tv/go?set
> class Set(list):
> def __init__(self, value = []):
> list.__init__([])
Tom,
Indeed, that first line of the Set constructor body is invoking the
constructor for the base class (list, in this case). The reason
that the value parameter is NOT being directly sent to the base
class is that there is a desire to avoid allowing potentially
duplicate elements into something that is representing a set.
However, it was entirely unnecessary for them to send an empty list
as a parameter. It would suffice to have written
list.__init__()
It is important to have the call to the base class initializer
because we need to allow for the internal state of the underlying
list to be properly intitialized.
Please note that the original source for this from viner.tv
has an important fourth line:
class Set(list):
def __init__(self, value = []):
list.__init__([])
self.concat(value) # copies mutable default
That fourth line uses a custom method defined later to insert
designated values into the set while making sure to avoid
duplicates.
With regard,
Michael
More information about the Tutor
mailing list