AlgoViz

Multiple inheritance

hard 50 min

A class with several parent classes gets the types, the methods and the fields of all of them.

Watch lesson4:37

Verify

Trace the line.

The point: write the order down and walk along it, down for the calls and up for the returns.

Making Noor

StepClassReceivesKeepsPasses on
1WorkingStudentname, school, companynothingall three
2Studentschool, restschool (on the way back)name, company
3Employeecompany, restcompanyname
4Personname, restnamenothing
5objectnothing
Fields are set on the way back: first name, then company, then school. This is the order in vars(noor).

Checks for every join class

  1. 1

    Print the MRO

    Is the class that should wrap left of the wrapped one?

  2. 2

    Count constructors

    Each parent exactly once. Put a counter into a test.

  3. 3

    Look at the fields

    vars(obj) shows every field once. A missing one means that somebody did not call super().

  4. 4

    List shared names

    Compare the public names of the parents. For each shared one: same promise or only the same word?

  5. 5

    Swap the parents

    If the tests still pass, the order does not matter. If not, write a comment that says why.

Python
def shared_names(*parents):    seen = {}    for p in parents:        for c in p.__mro__[:-1]:                      # without object            for name in vars(c):                if not name.startswith("__"):                    seen.setdefault(name, set()).add(c.__name__)    return {n: sorted(cs) for n, cs in seen.items() if len(cs) > 1}class Printer:    def start(self): ...    def print_job(self): ...class Scanner:    def start(self): ...    def scan(self): ...print(shared_names(Printer, Scanner))                 # {'start': ['Printer', 'Scanner']}
A small detector for shared names. Run it in a test for your join classes.
Edit and run it in your browser