6
# Python 3
class Point(tuple):
    def __init__(self, x, y):
        super().__init__((x, y))

Point(2, 3)

would result in

TypeError: tuple() takes at most 1 argument (2 given)

Why? What should I do instead?

max
  • 49,282
  • 56
  • 208
  • 355
  • 2
    possible duplicate of [Subclassing Python tuple with multiple __init__ arguments](http://stackoverflow.com/questions/1565374/subclassing-python-tuple-with-multiple-init-arguments) – Lennart Regebro Jan 28 '11 at 11:36

1 Answers1

10

tuple is an immutable type. It's already created and immutable before __init__ is even called. That is why this doesn't work.

If you really want to subclass a tuple, use __new__.

>>> class MyTuple(tuple):
...     def __new__(typ, itr):
...             seq = [int(x) for x in itr]
...             return tuple.__new__(typ, seq)
... 
>>> t = MyTuple((1, 2, 3))
>>> t
(1, 2, 3)
user225312
  • 126,773
  • 69
  • 172
  • 181
  • 1
    Ah, so my `Point(2,3)` looks for a `__new__` method in `Point`, fails to find it, invokes `tuple.__new__(Point,2,3)` which fails since it doesn't simply pass arbitrary number of arguments to `__init__` like a user-defined class would, but actually requires a single iterator to properly initialize `tuple`, correct? The code does not even get to the `Point.__init__(self, 2, 3)` call; that call, if it did occur, would be incorrect too since `tuple` does not have `__init__`, and so `object.__init__` would just silently do nothing? – max Jan 28 '11 at 17:54