Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem subclassing builtin type

# 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?

like image 700
max Avatar asked Jan 28 '11 10:01

max


1 Answers

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)
like image 190
user225312 Avatar answered Oct 03 '22 00:10

user225312