# Python 3
class Point(tuple):
def __init__(self, x, y):
super().__init__((x, y))
Point(2, 3)
結果として
TypeError: tuple() は最大で 1 つの引数を取ります (2 つ指定)
なんで?代わりに何をすべきですか?
# Python 3
class Point(tuple):
def __init__(self, x, y):
super().__init__((x, y))
Point(2, 3)
結果として
TypeError: tuple() は最大で 1 つの引数を取ります (2 つ指定)
なんで?代わりに何をすべきですか?
tuple
不変型です。呼び出される前にすでに作成されており、不変__init__
です。これが機能しない理由です。
本当にタプルをサブクラス化したい場合は、__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)