我在 python 2.7 中创建了一个类。然后我创建了我创建的类的子类。为了定义子类的init,我使用了super函数,但是当我在python上运行它时,它给出了错误消息:
class B:
def __init__(self, l):
self.p = l
self.d = len(l)
class C(B):
def __init__(self, l):
super(C,self).__init__(l)
当我对我输入的某个变量 l 运行 C(l) 时,它显示一条错误消息,如下所示:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "class_sample.py", line 12, in __init__
super(C,self).__init__(l)
TypeError: must be type, not classobj
>>>
最佳答案
根据python 2.7 documentation on super(..)
function :
Note: super() only works for new-style classes.
而您的 B
类是旧式类。因此,将 class B:
更改为 class B(object)
可以解决问题。这是一个稍微编辑过的示例:
class B(object):
def __init__(self, l):
self.p = l
self.d = len(l)
class C(B):
def __init__(self, l):
super(C,self).__init__(l)
c = C([])
print c.d
关于Python 2.7 super 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25486826/