Search code examples
pythonclasspython-2.7multiple-inheritancesuper

Python Multiple Inheritance Example


I have this situation

class A(object):

    def __init__(self):
        self.x = 0
        self.y = 0

class B(A):
    def __init__(self):
        super(B, self).__init__()

    def method(self):
        self.x += 1

class C(A):

    def __init__(self):
        super(C, self).__init__()

    def method(self):
        self.y += 1

class D(B, C):

    def __init__(self):
        super(D, self).__init__()

    def method(self):
        print self.x
        print self.y

I want D to print 1 for both x and y, but it is printing 0.
I don't fully understand multiple inheritance/super/etc... and while I have been trying to read the docs, an explanation on the example would be very helpful to me.

Thanks!


Solution

  • When you create a D object , it will never call method that named 'method'. It will just call parent's 'init' method. So x or y will not change.