0

我试过阅读 python2.7文档,但不幸的是没有机会理解。

为什么会这样?它如何与 init 内部的 MRO 和 super call 连接?

第一个例子:

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 内部的 super 调用:

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__
4

0 回答 0