Let's say:
For each class, we arrange all supertypes into an ordered list without repetitions, and insert the class itself at the start of the list. We put this list in an class attribute called
supertypes_listfor our use later.We use a different technique to implement
do_your_stuff()for our classes.Example 2.4. Call next method technique
class B(A): def do_your_stuff(self): next_class = self.find_out_whos_next() next_class.do_your_stuff(self) # do stuff with self for B def find_out_whos_next(self): l = self.supertypes_list # l depends on the actual instance mypos = l.index(B)
# Find this class in the list
return l[mypos+1] # Return the next one
The interesting part is how we
find_out_whos_next(), which depends on which instance we are working with. Note that:Depending on whether we passed an instance of
Dor ofB,next_classabove will resolve to eitherCorA.We have to implement
find_out_whos_next()for each class, since it has to have the class name hardcoded in it (see
above). We cannot use
self.__class__here. If we have calleddo_your_stuff()on an instance ofD, and the call is traversing up the hierarchy, thenself.__class__will beDhere.
Using this technique, each method is called only once. It
appears clean, but seems to require too much work. Fortunately for us,
we neither have to implement find_out_whos_next()
for each class, nor set the supertypes_list, as
Python does both of these things.