1

when searching for attributes, Python looks in object g 1st. If I number each class named in the drawing below (2=2nd, 3=3rd, etc.) Could anyone show me the order in which all these classes are searched.

class A : pass 
class B : pass 
class C(A,object): pass
class D: pass
class E(D,B): pass
class F(B,C): pass
class G(E,F): pass

g = G()
Jign
  • 149
  • 1
  • 1
  • 10

1 Answers1

3

This order:

>>> G.__mro__
(<class '__main__.G'>, <class __main__.E at 0x028412D0>, <class __main__.D at 0x
02841298>, <class '__main__.F'>, <class __main__.B at 0x02841260>, <class '__mai
n__.C'>, <class __main__.A at 0x02841228>, <type 'object'>)
>>> print ', '.join(klass.__name__ for klass in G.__mro__)
G, E, D, F, B, C, A, object

If you want to know how that order is computed, there isn't a good, short answer. The incomplete, short answer is that Python ensures that subclasses come before superclasses and classes earlier in a list of base classes come before classes later in a list of base classes. The long answer is the 40-page document about C3 linearization on python.org, although the actual algorithm isn't 40 pages.

user2357112
  • 260,549
  • 28
  • 431
  • 505