在python2.7中绕过构造函数

2024-10-02 00:22:32 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下继承链:

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的构造函数,即output

INHERIT2
BASE
5
6

有办法吗?你知道吗

编辑我不能更改基/Inherit1,我只能编辑Inherit2。你知道吗


Tags: self编辑outputbaseobjectinitdefclass
1条回答
网友
1楼 · 发布于 2024-10-02 00:22:32

编辑:哈,我们都难倒的时候,有一个非常简单的解决办法。你知道吗

调用super时,将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)

相关问题 更多 >

    热门问题