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

Point(2, 3)

結果として

TypeError: tuple() は最大で 1 つの引数を取ります (2 つ指定)

なんで?代わりに何をすべきですか?

4

1 に答える 1

10

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)
于 2011-01-28T10:51:42.553 に答える