子类化builtin typ时出现问题

2024-04-19 23:53:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Point(2, 3)

会导致

TypeError: tuple() takes at most 1 argument (2 given)

为什么?我该怎么办?在


Tags: selfmostinitdefargumentgivenatclass
1条回答
网友
1楼 · 发布于 2024-04-19 23:53:05

tuple是一个不可变的类型。在调用__init__之前,它已经被创建并且是不可变的。这就是为什么这行不通。在

如果您真的想子类化元组,请使用^{}。在

>>> 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)

相关问题 更多 >