[Tutor] How to subclass built-in types?

Gregor Lingl glingl@aon.at
Sun, 29 Sep 2002 18:40:51 +0200


Hi pythonistas!

This time I have the following question:

If I subclass the built-in type list as follows:

 >>> class L(list):
    pass

 >>> a = L()
 >>> a
[]
 >>> b = L([1,2,3])
 >>> b
[1, 2, 3]
 >>> c = L("xyz")
 >>> c
['x', 'y', 'z']
 >>>

So L seems to use list as a constructor or at least
behaves as if.

Next example:

 >>> class M(list):
    def __init__(self, x):
        self.x = x

       
 >>> e = M(3)
 >>> e
[]
 >>> e.x
3

This constructor only constructs empty lists.
Now, how do I define a constructor, which, for instance as
the first argument takes a sequenze to initialize itself (as
a list) and more arguments for other purposes.

This class should behave like the following:

 >>> class N(list):
    def __init__(self, seq, x):
        self.x = x
        self.extend(seq)

       
 >>> f = N( (3,4,5), "C" )
 >>> f
[3, 4, 5]
 >>> f.x
'C'
 >>>

However, I think that this is not the canonical way to do things like
this, because it depends on the existence of  the extend - method,
which exists only for lists, whereas the given problem is one
which applies to subclassing built-in types in general.

Who knows how to do it "according to the rules"?

Regards, Gregor