为什么Python中的基类需要扩展对象?

时间:2014-12-10 04:29:52

标签: python inheritance

我正在寻找一个明确的解释,如果我想使用object

,我的基类必须扩展super的原因
# Without extending object, this code will fail with 
# TypeError: must be type, not classobj
class A(object):
  def __init__(self):
    print "Called A.__init__"

class AChild(A):
  def __init__(self):
    super(AChild, self).__init__()
    print "Called AChild.__init__"

AChild()

这可以按预期工作,但如果删除object,它会抛出提到的异常。我正在使用Python 2.7.8。请随时将我链接到任何相关问题,但我没有找到一个快速搜索的好答案

1 个答案:

答案 0 :(得分:1)

这是因为通过扩展object,您正在使用支持使用super所需的新样式类,这是在向Python引入新样式类的同时添加的。 / p>

根据此answer中的信息,旧样式类具有简单的深度优先方法解析顺序,因此不需要此函数,这可能就是为什么它不是 然后包括在内。但是,在添加多重继承时,super现在是调用超类的推荐方法,因为MRO更复杂。