[Tutor] problem when subclassing tuple

Karl Pflästerer sigurd at 12move.de
Sat Jan 24 17:21:13 EST 2004


On 24 Jan 2004, Gregor Lingl <- glingl at aon.at wrote:

> I'm trying to define a fancy subclass of tuple: ;-)

> class Vec(tuple):
>    def __init__(self, v):
>        tuple.__init__(v)

> and some more methods ...

> Works fine.

> Actually I want my Vec class objects to be constructed
> like this:

> a = Vec(1,2,3)

Maybe I don't understand what you want to achieve exactly but what about
overriding __new__ instead of __init__? (I had the idea when I read
descintro.html)
class vec(tuple):
    def __new__(cls, x,y,z):
        return tuple.__new__(cls, [x,y,z])



> But when I tried to overwrite the constructor of tuple
> with a new one with a different number of parameters, I failed:


[...]
> So does someone know a way how to define a subclass of
> tuple so its objects can be constructed the way
> mentioned above?

Perhaps like the above solution.

> Hints as well as solutions are highly appreciated,
> pointers to appropriate sections of the docs also.

,----[ descintro.html ]
|     * If you want to change the constructor's signature, you often have to override both
|        __new__ and __init__ to accept the new signature. However, most built-in types ignore
|        the arguments to the method they don't use; in particular, the immutable types (int,
|        long, float, complex, str, unicode, and tuple) have a dummy __init__, while the
|        mutable types (dict, list, file, and also super, classmethod, staticmethod, and
|        property) have a dummy __new__. The built-in type 'object' has a dummy __new__ and a
|        dummy __init__ (which the others inherit). The built-in type 'type' is special in many
|        respects; see the section on [55]metaclasses.
`----

This writing about the dummy init method seems to describe your problem.
If that won't help perhaps we have to dig in metaclasses; would be
interesting I didn't explore them myself yet.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list