Python 2.7 super 错误

标签 python python-2.7 typeerror

我在 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/

相关文章:

python - 按字母顺序对元组排序

javascript - 在 Javascript 中,您可以在同一类的另一个函数中调用该类的函数吗?

python - grequests 以什么方式异步?

python - concurrent.futures ThreadPoolExecutor 等待失败?

python - 如何在Python中逐个字符地遍历unicode泰米尔语单词?

python-2.7 - PyInstaller 2.0 类型错误 : compile() expected string without bull bytes

python - 如何修复 "TypeError"- 'dict_keys' 对象不可订阅?

python - 从 python 中的 feedparser 解析不同的日期格式?

python - 根据嵌套字典值对 Python 字典进行排序

python - 添加第二个 x_axis 覆盖标题