[Tutor] problem when subclassing tuple

Gregor Lingl glingl at aon.at
Sat Jan 24 12:59:07 EST 2004


Hi Pythonistas!

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)

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

First I tried to pass three arguments:

class Vec2(tuple):
   def __init__(self, x, y, z):
       tuple.__init__((x,y,z))

trying this out, I get:

>>> v = Vec2(1,2,3)
Traceback (most recent call last):
 File "<pyshell#24>", line 1, in ?
   v = Vec2(1,2,3)
TypeError: tuple() takes at most 1 argument (3 given)

Same result when trying a starred parameter:

class Vec3(tuple):
   def __init__(self, *args):
       tuple.__init__(args)

>>> v = Vec3(1,2,3,4,5)
Traceback (most recent call last):
 File "<pyshell#25>", line 1, in ?
   v = Vec3(1,2,3,4,5)
TypeError: tuple() takes at most 1 argument (5 given)

Trying out a recipe from the cookbook also failed:

class Vec4(tuple):
   def __init__(self, *args):
       super(Vec4,self).__init__(args)

>>> v = Vec4(1,2,3,4,5)
Traceback (most recent call last):
 File "<pyshell#38>", line 1, in ?
   v = Vec4(1,2,3,4,5)
TypeError: tuple() takes at most 1 argument (5 given)

So it seems, that one cannot overwrite the constructor of
tuple (or of built-in types in general)?

Maybe I'm on a completely wrong road.
So does someone know a way how to define a subclass of
tuple so its objects can be constructed the way
mentioned above?

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

Regards and thanks in advance

Gregor


P. S.: No homework assignment  ;-)









More information about the Tutor mailing list