绕过Python 2.7中的构造函数

时间:2016-05-12 01:21:02

标签: python inheritance

假设我有以下继承链:

class Base(object):
    def __init__(self, a=1, b=2):
        print "BASE"
        print a
        print b

class Inherit1(Base):
    def __init__(self, a=3, b=4):
        print "INHERIT1"
        super(Inherit1, self).__init__(a=a, b=b)

class Inherit2(Inherit1):
    def __init__(self, a=5, b=6):
        print "INHERIT2"
        super(Inherit2, self).__init__(a=a, b=b)

Inherit2()

它会输出:

INHERIT2
INHERIT1
BASE
5
6

但是我想绕过Inherit1的构造函数,即输出

INHERIT2
BASE
5
6

有没有办法这样做?

编辑我无法更改Base / Inherit1,我只能编辑Inherit2。

1 个答案:

答案 0 :(得分:1)

编辑:当我们有一个非常简单的解决方案时,我们都会感到难过。

如此调用超级变更super(Inherit2, self)super(Inherit1, self)

class Inherit2(Inherit1):
    def __init__(self, a=5, b=5):
        print "INHERIT2"
        super(Inherit1, self).__init__(a=a, b=b)
相关问题