【问题标题】:Python 2.7 super error [duplicate]Python 2.7 超级错误 [重复]
【发布时间】:2014-10-18 15:47:00
【问题描述】:

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

【问题讨论】:

  • Class B 需要继承自新式类的对象。
  • 在 SO 和其他地方大约有 900 个重复;学会用谷歌搜索你的错误信息。

标签: python python-2.7 typeerror


【解决方案1】:

根据python 2.7 documentation on super(..) function:

注意: super() 仅适用于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

【讨论】:

  • 不客气!请注意,您可以将回复标记为答案以帮助其他访问者并感谢我;)
猜你喜欢
  • 2016-10-30
  • 2016-10-19
  • 2016-10-06
  • 1970-01-01
  • 2016-04-19
  • 2021-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多