Problem subclassing tuple

sismex01 at hebmex.com sismex01 at hebmex.com
Tue Apr 29 21:27:25 CEST 2003


> From: John Wilson [mailto:tug at wilson.co.uk]
> Sent: Tuesday, April 29, 2003 2:22 PM
> 
> Success!!!
> 
> class Holder(tuple):
>     def __new__(cls, *args, **kargs):
>         return tuple.__new__(cls, args)
> 
> 
> is the way to do it for a tuple :))))))
> 
> John Wilson
>

Heh, excellent :-)

You might want to make it "cooperative", that is,
instead of using "tuple.__new__", use
"super(Holder,cls).__new__"

This delegates the search for the superclass to the
function super(); and that gives you the ability
to have multiple inheritance, since super() will
"do the right thing" when getting your current
class' superclass; so every class which defines
a __new__ method has it called.

:-)

Like this:

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Holder(tuple):
...   def __new__(klass, *args, **kwargs):
...     return super(Holder,klass).__new__(klass, args)
...
>>> h = Holder(1,2,3)
>>>
>>> h
(1, 2, 3)
>>> type(h)
<class '__main__.Holder'>
>>>


-gus





More information about the Python-list mailing list