Search code examples
pythonclassinheritancemultiple-inheritance

How to exclude __init__ of parent class but include __init__ of parent of parent class?


Is there any way possible that the Third class can inherit the First class, as well as methods of Second class except the __init__ method of Second class?

class First(object):
    def __init__(self):
        super().__init__()
        print("first")

    def f1(self):
        print("f1")


class Second(First):
    def __init__(self):
        super().__init__()
        print("second")

    def f2(self):
        print("f2")


class Third(Second):
    def __init__(self):
        super().__init__()
        print("third")
        self.f1()
        self.f2()
        self.f3()

    def f3(self):
        print("f3")


Third()

Current output

first
second
third
f1
f2
f3

Expecting output

first
third
f1
f2
f3

Solution

  • Third is already overriding the __init__ method, so all you have to do is use the explicit class name whose __init__ you want to use instead of calling super.

    # Inside Third.__init__
    First.__init__(self)