Python Call Parent Method Multiple Inheritance

2019-02-16 13:23发布

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?

2条回答
你好瞎i
2楼-- · 2019-02-16 13:52

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
查看更多
乱世女痞
3楼-- · 2019-02-16 14:12

Add super() call's in other classes as well except C. Since D's MRO is

>>> D.__mro__
(<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <type 'object'>)

You don't need super call in C.

Code:

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

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


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()

Output:

foo from D
foo from A, call from D
foo from B, call from A
foo from C, call from B
查看更多
登录 后发表回答