2011-01-28 46 views
6
# 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)

为什么?我该怎么做呢?

+2

可能重复(http://stackoverflow.com/questions/1565374/subclassing-python-tuple-with-multiple-init-arguments) – 2011-01-28 11:36:10

回答

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) 
[多__init__参数子类的Python元组]的
+1

啊,所以我`Point(2,3)`在`Point`中寻找`__new__`方法,但是找不到它,调用`tuple .__ new __(Point,2,3)`,因为它不会简单地传递任意数量的`__init__`的参数就像用户定义的类一样,但实际上需要一个迭代器正确初始化`元组',对吗?该代码甚至没有进入`Point .__ init __(self,2,3)`调用;那个调用,如果它真的发生了,也会是不正确的,因为`tuple`没有`__init__`,所以`object .__ init__`只会默默无闻呢? – max 2011-01-28 17:54:51