Python忽略了在继承类中提供给元组的参数的默认值

AIG*_*110 5 python inheritance constructor tuples

这里有一些代码来演示我在说什么.

class Foo(tuple):
   def __init__(self, initialValue=(0,0)):
      super(tuple, self).__init__(initialValue)

print Foo()
print Foo((0, 0))
Run Code Online (Sandbox Code Playgroud)

我希望两个表达式产生完全相同的结果,但该程序的输出是:

()
(0, 0) 
Run Code Online (Sandbox Code Playgroud)

我在这里不理解什么?

Dol*_*000 10

那是因为tuple类型不关心参数__init__,而只关心那些参数__new__.这将使它工作:

class Bar(tuple):
    @staticmethod
    def __new__(cls, initialValue=(0,0)):
        return tuple.__new__(cls, initialValue)
Run Code Online (Sandbox Code Playgroud)

这个的基本原因是,由于元组是不可变的,所以在你甚至可以在Python级别看到它们之前,需要预先构造它们的数据.如果数据是通过提供的__init__,你基本上会在自己的开头有一个空元组__init__,然后在你调用时改变super().__init__().