# Simple Python program to demonstrate how Python handles multiple inheritance # We have classes A, B, C, and D. B and C inherit from A. # D inherits from B and C. # Both B and C define a method foo() and the program reveals # what Python does in this situation. # The print statements also show that Python is able to handle the # fact that A is referenced twice by the inheritance hierarchy and # only creates one instance of A that is reference by both B and C. # You can run this program by typing "python multi.py". # Try creating a similar program in another language that supports # multiple inheritance and see if that langauge makes different # choices than Python. class A(object): def __init__(self): print("In A's __init__") self.w = 10 class B(A): def __init__(self): print("In B's __init__") super(B, self).__init__() self.x = 20 def foo(self): print("B's foo") class C(A): def __init__(self): print("In C's __init__") super(C, self).__init__() self.y = 30 def foo(self): print("C's foo") # Try uncommenting the next line and commenting the one below it # to see how the order of listing the superclasses affects # the method invocation of foo() class D(B, C): # class D(C, B): def __init__(self): print("In D's __init__") super(D, self).__init__() self.z = 40 d = D() for i in ["w", "x", "y", "z"]: print("d.%s = %d" % (i, getattr(d, i))) d.foo()