>> class P: ... def __init__(self, argp): ... -6ren">
gpt4 book ai didi

python - 具有 "super"属性的 Python 单继承中的 TypeError

转载 作者:太空狗 更新时间:2023-10-29 17:30:18 29 4
gpt4 key购买 nike

没想到Python2.7的继承如此反人类。为什么下面的代码给我一个 TypeError?

>>> class P:
... def __init__(self, argp):
... self.pstr=argp
...
>>> class C(P):
... def __init__(self, argp, argc):
... super.__init__(self,argp)
... self.cstr=argc
...
>>> x=C("parent","child")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
TypeError: descriptor '__init__' requires a 'super' object but received a 'instance'

然后我改成这2个,还是模糊的错误:

>>> class C(P):
... def __init__(self, argp, argc):
... super().__init__(self,argp)
... self.cstr=argc
...
>>> x=C("parent", "child")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
TypeError: super() takes at least 1 argument (0 given)


>>> class C(P):
... def __init__(self, argp, argc):
... super(P).__init__(self,argp)
... self.cstr=argc
...
>>> x=C("parent", "child")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
TypeError: must be type, not classobj

--------添加--------

还是不行,如下图

>>> class P:
... def __init__(self, argp):
... self.pstr=argp
...
>>> class C(P):
... def __init__(self, arg1, arg2):
... super(C, self).__init__(arg1)
... self.cstr=arg2
...
>>> z=C("PPP", "CCC")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
TypeError: must be type, not classobj

------------ADD2------------

似乎下面的 2 个代码片段都有效,有什么区别?顺便说一句,什么时候应该使用新样式类旧样式类

>>> class C(P):
... def __init__(self, argp, argc):
... super(C,self).__init__(argp) #<------ C and self
... self.cstr=argc
...
>>> class C(P):
... def __init__(self, argp, argc):
... super(P,C).__init__(argp) #<----- P and C
... self.cstr=argc

最佳答案

根据您使用的 Python 版本,您的问题可能有两种回答。

python 2.x

super 必须这样调用 (example for the doc) :

class C(B):
def method(self, arg):
super(C, self).method(arg)

在您的代码中,这将是:

>>> class P(object):    # <- super works only with new-class style
... def __init__(self, argp):
... self.pstr=argp
...
>>> class C(P):
... def __init__(self, argp, argc):
... super(C, self).__init__(argp)
... self.cstr=argc

在这种情况下,您也不必在参数中传递 self

python 3.x

在 Python 3.x 中,super 方法得到了改进:您可以 use it without any parameters (现在两者都是可选的)。此解决方案也可以工作,但仅适用于 Python 3 及更高版本:

>>> class C(P):
... def __init__(self, argp, argc):
... super().__init__(argp)
... self.cstr=argc

关于python - 具有 "super"属性的 Python 单继承中的 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21063228/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com