problem subclassing builtin type
Asked Answered
B

1

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?

Banner answered 28/1, 2011 at 10:44 Comment(1)
possible duplicate of Subclassing Python tuple with multiple init argumentsBlameless
V
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)
Vitrain answered 28/1, 2011 at 10:51 Comment(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?Banner

© 2022 - 2024 — McMap. All rights reserved.