Possible Duplicate:
Subclassing Python tuple with multiple __init__ arguments
I want to define a class which inherits from tuple, and I want to be able to instantiate it using a syntax not supported by tuple. For a simple example, let’s say I want to define a class MyTuple which inherits from tuple, and which I can instantiate by passing two values, x and y, to create the (my) tuple (x, y). I’ve tried the following code:
class MyTuple(tuple):
def __init__(self, x, y):
print("debug message")
super().__init__((x, y))
But when I tried, for example, MyTuple(2, 3) I got an error: TypeError: tuple() takes at most 1 argument (2 given). It seems my __init__ function was not even called (based on the error I got and on the fact my “debug message” was not printed).
So what’s the right way to do this?
I’m using Python 3.2.
One of the difficulties of using
superis that you do not control which classes’s method of the same name is going to be called next. So all the classes’ methods have to share the same call signature — at least the same number of items. Since you are changing the number of arguments sent to__new__, you can not usesuper.Or as Lattyware suggests, you could define a namedtuple,