Search code examples
pythonclassinheritancemultiple-inheritance

Python Call Parent Method Multiple Inheritance


So, i have a situation like this.

class A(object):
    def foo(self, call_from):
        print "foo from A, call from %s" % call_from


class B(object):
    def foo(self, call_from):
        print "foo from B, call from %s" % call_from


class C(object):
    def foo(self, call_from):
        print "foo from C, call from %s" % call_from


class D(A, B, C):
    def foo(self):
        print "foo from D"
        super(D, self).foo("D")

d = D()
d.foo()

The result of the code is

foo from D
foo from A, call from D

I want to call all parent method, in this case, foo method, from D class without using super at the parent class like A. I just want to call the super from the D class. The A, B, and C class is just like mixin class and I want to call all foo method from D. How can i achieve this?


Solution

  • You can use __bases__ like this

    class D(A, B, C):
        def foo(self):
            print("foo from D")
            for cls in D.__bases__:
                cls().foo("D")
    

    With this change, the output will be

    foo from D
    foo from A, call from D
    foo from B, call from D
    foo from C, call from D