Built-in Type Subclassing Problem

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

will result in

TypeError: tuple () takes no more than 1 argument (2)

Why? What should I do instead?

+6
python subclassing built-in-types
source share
1 answer

tuple is an immutable type. It is already created and immutable before __init__ even called. That is why it does not 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) 
+10
source share

All Articles