Upgrade to Pro — share decks privately, control downloads, hide ads and more …

On Being Super()

abingham
September 20, 2014

On Being Super()

A short description of the details of how Python's super() works.

abingham

September 20, 2014
Tweet

More Decks by abingham

Other Decks in Programming

Transcript

  1. ON BEING S U P E R ( ) Austin

    Bingham Sixty North AS 0
  2. MRO: AN ORDERING OF AN INHERITANCE GRAPH I n [

    1 ] : c l a s s A : p a s s I n [ 2 ] : c l a s s B ( A ) : p a s s I n [ 3 ] : c l a s s C ( A ) : p a s s I n [ 4 ] : c l a s s D ( B , C ) : p a s s I n [ 5 ] : D . m r o ( ) O u t [ 5 ] : [ _ _ m a i n _ _ . D , _ _ m a i n _ _ . B , _ _ m a i n _ _ . C , _ _ m a i n _ _ . A , o b j e c t ]
  3. C3: THE ALGORITHM FOR CALCULATING MRO 1. Derived classes come

    before base classes 2. Base class definition order is preserved 3. 1 and 2 are preserved at all points in the graph
  4. C3: SOME INHERITANCE GRAPHS ARE ILLEGAL! I n [ 1

    ] : c l a s s A : p a s s I n [ 2 ] : c l a s s B ( A ) : p a s s I n [ 3 ] : c l a s s C ( A ) : p a s s I n [ 4 ] : c l a s s D ( B , A , C ) : p a s s - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - T y p e E r r o r T r a c e b a c k ( m o s t r e c e n t c a l l l a s t ) < i p y t h o n - i n p u t - 4 - 4 b f 7 3 2 f a d a a 7 > i n < m o d u l e > ( ) - - - - > 1 c l a s s D ( B , A , C ) : p a s s T y p e E r r o r : C a n n o t c r e a t e a c o n s i s t e n t m e t h o d r e s o l u t i o n o r d e r ( M R O ) f o r b a s e s A , C
  5. FINALLY, SUPER() Given a method resolution order and a class

    C in that MRO, super() gives you an object which resolves methods using only the part of the MRO which comes after C.
  6. SUPER-PROXIES: JUST REGULAR OLD OBJECTS I n [ 2 8

    ] : s = s u p e r ( B , D ( ) ) I n [ 2 9 ] : t y p e ( s ) O u t [ 2 9 ] : s u p e r I n [ 3 0 ] : s . _ _ t h i s c l a s s _ _ O u t [ 3 0 ] : _ _ m a i n _ _ . B
  7. IN SUMMARY… 1. Python calculates an MRO for all classes

    2. C3 is the algorithm for determining the MRO 3. super() requires an MRO and a starting point in the MRO 4. super-proxies find the first class in the remaining MRO which supports the requested method