Python Call Parent Method Multiple Inheritance

前端 未结 3 1002
一个人的身影
一个人的身影 2021-01-04 04:40

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


        
3条回答
  •  既然无缘
    2021-01-04 04:46

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

    >>> D.__mro__
    (, , , , )
    

    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
    

提交回复
热议问题