# 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)
为什么?我该怎么做呢?
解决方法
元组是一个不可变类型.在__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,3)