在多级和多级继承中使用super()

时间:2020-03-24 07:18:08

标签: python python-3.x oop inheritance multiple-inheritance

我是多重继承的新手。我正在尝试执行一个示例:

class First(object):
    def __init__(self):
        super().__init__()
        print("first")

class Second(object):
    def __init__(self):
        super().__init__()
        print("second")

class Third(First, Second):
    def __init__(self):
        super().__init__()
        print("third")
Third()

我得到的输出是:

second
first
third
<__main__.Third at 0x21bbaf2fc88>

任何人都可以解释一下此输出的原因吗? 我期望的输出是:

first
second
third

由于第三类的__init __()会调用第一类的__init __()(因为它在父列表中是第一个),它将先打印第二类的__init __(),然后再打印第三类的__init __()。

MRO会打印出我所期望的。

print(Third.__mro__)

打印

(__main__.Third, __main__.First, __main__.Second, object)

2 个答案:

答案 0 :(得分:0)

如果您在致电super().__init__()前先进行print(xxx) ,则显示的顺序是正确的。

如果您希望订单显示在“例外”标签中,则可以将每个print(xxx)换成super().__init__(),这样可以解决该问题。

代码:

class First(object):
    def __init__(self):
        print("first")
        super().__init__()

class Second(object):
    def __init__(self):
        print("second")
        super().__init__()

class Third(First, Second):
    def __init__(self):
        print("third")            
        super().__init__()
Third()

答案 1 :(得分:0)

这似乎只是在__init__中进行打印时的人工产物。您当前的代码会在之后打印,并调用super().__init__,因此继承层次结构将以相反的顺序打印出来。如果在超级调用之前进行打印,则其顺序将与MRO相同。如果同时打印两种方式,可能最容易理解:

class First(object):
    def __init__(self):
        print("first (top)")
        super().__init__()
        print("first (bottom)")

class Second(object):
    def __init__(self):
        print("second (top)")
        super().__init__()
        print("second (bottom)")

class Third(First, Second):
    def __init__(self):
        print("third (top)")
        super().__init__()
        print("third (bottom)")

现在Third()的输出应为:

third (top)
first (top)
second (top)
second (bottom)
first (bottom)
third (bottom)

您看到的输出<__main__.Third ...>并不是由任何代码打印的,而是由交互式shell打印的。这是调用Third(类的实例)的结果。如果您执行了instance = Third(),您将不会看到,因为该值将存储到变量中,并且不会被打印出来。 REPL(读取评估打印循环)仅在以交互方式运行Python时运行,而不会在您导入或作为脚本运行的模块中进行任何额外的打印。