Question

This is more of a question of curiosity, rather than a serious issue:

I was playing around with multiple inheritance and came accross this:

>>> class A(object):
...     def __init__(self): print "A.__init__() called"
...
>>> class B(object, A): pass
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Cannot create consisten method resolution
order (MRO) for bases object, A

I get a TypeError. However, when I reverse the order of the multiple inheritance:

>>> class B(A, object): pass
>>> b = B()
A.__init__() called

It works fine. I assumed that in the first instance, the inheritance of object before A creates some kind of name ambiguity. Would anyone care to explain what is going on here?

Was it helpful?

Solution

A is inherited from object or subclass of object, it doesn't work. The MRO guarantees that leftmost bases are visited before rightmost ones - but it also guarantees that among ancestors if x is a subclass of y then x is visited before y. It's impossible to satisfy both of these guarantees in this case

Here is a similar question

Python: Problem with metaclasses in conjunction multiple inheritance

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top