__init__ 超类和子类之间的参数不匹配
__init__ argument mismatch between super and subclass
我正在尝试使 class 继承自 datetime.date
,调用 superclasses __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__
吗?在什么情况下我还需要调用 superclasses __new__
构造函数?
是的,你需要实现__new__
,并在超class上调用它;例如:
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]
我正在尝试使 class 继承自 datetime.date
,调用 superclasses __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__
吗?在什么情况下我还需要调用 superclasses __new__
构造函数?
是的,你需要实现__new__
,并在超class上调用它;例如:
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]