__初始化参数在超类和子类之间不匹配

2024-04-24 07:12:57 发布

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

我试图让一个类从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__构造函数?你知道吗


Tags: inmostnew参数datetimedateinityear
1条回答
网友
1楼 · 发布于 2024-04-24 07:12:57

是的,您需要实现__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]

相关问题 更多 >