xis
xis

Reputation: 24850

Bypassing constructor in Python 2.7

Suppose I have the following chain of 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()

It would output:

INHERIT2
INHERIT1
BASE
5
6

But I would like to bypass the constructor of Inherit1, i.e. output

INHERIT2
BASE
5
6

is there a way of doing so?

EDIT I cannot change Base/Inherit1, I can only edit Inherit2.

Upvotes: 1

Views: 78

Answers (1)

hostingutilities.com
hostingutilities.com

Reputation: 9519

Edit: Ha we where all stumped when there is a very easy solution.

When calling super change super(Inherit2, self) to super(Inherit1, self) like so

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

Upvotes: 1

Related Questions