-1

I have the following piece of code :-

class A(object):
    def __init__(self):
        print "I'm in A"

    def awesome_function(self):
        raise NotImplementedError

class B(A):
    def awesome_function(self):
        print "Implemented in B"

class C(object):
    def awesome_function(self):
        print "Implemented in C"

class D(A,C):
    def another_function(self):
        print "hello world"

class E(C,A):
    def another_function(self):
        print "hello world"

try:
    a = A()
    a.awesome_function()
except Exception as e:
    print "NotImplementedError"
    pass

try:
    b = B()
    b.awesome_function()
except Exception as e:
    print "NotImplementedError in b"

try:
    d = D()
    d.awesome_function()
except Exception as e:
    print "NotImplementedError in d"

try:
    e = E()
    e.awesome_function()
except Exception as s:
    print "NotImplementedError in e"

And the output I get is :-

I'm in A
NotImplementedError
I'm in A
Implemented in B
I'm in A
NotImplementedError in d
I'm in A
Implemented in C

Why does E work and D not work?

I would assume that functions get populated in a class's dict from left to right, in the order I mention in the inheritence. However, it seems like it's going from right to left?

The Nomadic Coder
  • 580
  • 1
  • 4
  • 16

1 Answers1

1

You can check the method resolution order:

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

As you see, class D goes to the superclass A first (and found the awesome_function method), which is the order you listed in the inheritance from left to right.

Young
  • 254
  • 1
  • 3
  • 10