__init__参数在超级和子类之间不匹配

时间:2015-02-04 22:06:25

标签: python inheritance python-3.x

我正在尝试从datetime.date继承一个类,调用超类__init__函数,然后在顶部添加一些变量,这些变量涉及在顶部使用第四个__init__参数年,月,日。

以下是代码:

class sub_class(datetime.date):    
    def __init__(self, year, month, day, lst):  
        super().__init__(year, month, day)
            for x in lst:
                # do stuff

inst = sub_class(2014, 2, 4, [1,2,3,4])

这会引发以下错误:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    inst = sub_class(2014, 2, 4, [1,2,3,4])
TypeError: function takes at most 3 arguments (4 given)

如果我删除最后一个参数,我会得到以下内容:

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    inst = sub_class(2014, 2, 4)
TypeError: __init__() missing 1 required positional argument: 'lst'

我认为这是由于__new____init__之间的不匹配造成的。但是我该如何解决呢?我需要重新定义__new__吗?在这种情况下,我还需要调用超类__new__构造函数吗?

1 个答案:

答案 0 :(得分:1)

是的,你需要实现__new__,并在超类上调用它;例如:

class sub_class(datetime.date):

    def __new__(cls, year, month, day, lst):
        inst = super(sub_class, cls).__new__(cls, year, month, day)
        inst.lst = lst
        return inst

使用中:

>>> s = sub_class(2013, 2, 3, [1, 2, 3])
>>> s
sub_class(2013, 2, 3)  # note that the repr isn't correct 
>>> s.lst
[1, 2, 3]