LemonMan
LemonMan

Reputation: 3143

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!

Upvotes: 0

Views: 755

Answers (3)

user10503784
user10503784

Reputation: 1

You can also call the method for the inherited classes within your D subclass class D(B, C):

def __init__(self):
    B.__init__(self)
    C.__init__(self)

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

Upvotes: 0

Blckknght
Blckknght

Reputation: 104712

If you override a method like method in your example, but still want to get the behavior of the base class as well as your own, you need to use super to call the version of the method you're overriding.

class A(object):
    def __init__(self):
        self.x = 0
        self.y = 0

    def method(self):  # we need a verion of method() to end the super() calls at
        pass

class B(A):
    def method(self):
        super(B, self).method() # call overridden version of method()
        self.x += 1

class C(A):
    def method(self):
        super(C, self).method() # here too
        self.y += 1

class D(B, C):
    def method(self):
        super(D, self).method() # and here
        print self.x
        print self.y

I've removed the unnecessary __init__ methods in your child classes. There's no need to override a method unless you're changing its behavior, and none of the later __init__ methods did anything other than call their predecessor.

Upvotes: 2

ugursogukpinar
ugursogukpinar

Reputation: 337

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.

Upvotes: 1

Related Questions