Problem subclassing tuple

John Wilson tug at wilson.co.uk
Tue Apr 29 15:08:39 EDT 2003


----- Original Message ----- 
From: "Terry Reedy" <tjreedy at udel.edu>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Tuesday, April 29, 2003 5:48 PM
Subject: Re: Problem subclassing tuple


[snip]

> Because tuples are immutable, one cannot mutate them in an init
> method, even to set the initial values.  So, as you apparently
> suspected, they are initialized in the __new__ method from a sequence.
> This is the source of the exception (see below). tuple.__init__ should
> be a no op.
> 
> >>> class Holder(tuple):
> ...      def __init__(self, *values):
> ...          print "Holder init entered"
> ...
> >>> Holder(1,2)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: tuple() takes at most 1 argument (2 given)
> # init not entered
> >>> Holder((1,2))
> Holder init entered
> (1, 2)
> 
> While Holder.__init__() cannot modify the value of self, it *can* add
> attributes (which surprised me a bit) so it can have a use.
> 
> >>> class Holder(tuple):
> ...     def __init__(self, seq):
> ...         self.y = 1
> ...
> >>> a=Holder((1,2))
> >>> a.y
> 1
> 
> I don't know what more you could do in a __new__ method.

Terry,
    I have found that I can subclass list OK. 

This will do for what I'm after.

    Thanks to all the contributors to this thread for all the info :-))

John Wilson
The Wilson Partnership
http://www.wilson.co.uk






More information about the Python-list mailing list