为什么超级调用会改变调用父类的init方法的行为?

时间:2016-08-06 08:27:23

标签: python method-resolution-order

我试过阅读python 2.7文档,但遗憾的是没有机会解决。

为什么会这样?它是如何与MRO和init内部的超级调用连接的?

第一个例子:

class SuperFirst(object):
    def __init__(self):
        super(SuperFirst, self).__init__()
        print "We were in SuperFirst's __init__"

class SuperSecond(object):
    def __init__(self):
        super(SuperSecond, self).__init__()
        print "We were in SuperSecond's __init__"

class JustThird(SuperFirst, SuperSecond):
    def __init__(self):
        super(JustThird, self).__init__()
        print "We were in JustThird's __init__"

JustThird()

输出:

We were in SuperSecond's __init__
We were in SuperFirst's __init__
We were in JustThird's __init__

现在让我们删除第一个父级的init中的超级调用:

class SuperFirst(object):
    def __init__(self):
        print "We were in SuperFirst's __init__"

class SuperSecond(object):
    def __init__(self):
        super(SuperSecond, self).__init__()
        print "We were in SuperSecond's __init__"

class JustThird(SuperFirst, SuperSecond):
    def __init__(self):
        super(JustThird, self).__init__()
        print "We were in JustThird's __init__"

JustThird()

输出:

We were in SuperFirst's __init__
We were in JustThird's __init__

现在只保留在第一个父母中:

class SuperFirst(object):
    def __init__(self):
        super(SuperFirst, self).__init__()
        print "We were in SuperFirst's __init__"

class SuperSecond(object):
    def __init__(self):
        print "We were in SuperSecond's __init__"

class JustThird(SuperFirst, SuperSecond):
    def __init__(self):
        super(JustThird, self).__init__()
        print "We were in JustThird's __init__"

JustThird()

输出:

We were in SuperSecond's __init__
We were in SuperFirst's __init__
We were in JustThird's __init__

现在从父母双方删除:

class SuperFirst(object):
    def __init__(self):
        print "We were in SuperFirst's __init__"

class SuperSecond(object):
    def __init__(self):
        print "We were in SuperSecond's __init__"

class JustThird(SuperFirst, SuperSecond):
    def __init__(self):
        super(JustThird, self).__init__()
        print "We were in JustThird's __init__"

JustThird()

输出:

We were in SuperFirst's __init__
We were in JustThird's __init__

0 个答案:

没有答案