Different Sets of Arguments

Manage different sets of arguments

This is going to make things complicated as we return to our Friend cooperative multiple inheritance example. In the __init__() method for the Friend class, we were originally delegating initialization to the __init__() methods of both parent classes, with different sets of arguments:

Contact.__init__(self, name, email)
AddressHolder.__init__(self, street, city, state, code)

How can we manage different sets of arguments when using super()? We only really have access to the next class in the MRO sequence. Because of this, we need a way to pass the extra arguments through the constructors so that subsequent calls to super(), from other mixin classes, receive the right arguments.

It works like this. The first call to super() provides arguments to the first class of the MRO, passing the name and email arguments to Contact.__init__(). Then, when Contact.__init__() calls super(), it needs to be able to pass the address-related arguments to the method of the next class in the MRO, which is AddressHolder.__init__().

This problem often manifests itself anytime we want to call superclass methods with the same name, but with different sets of arguments. Collisions often arise around the special method names. Of these, the most common example is having a different set of arguments to various __init__() methods, as we’re doing here.

Handle functions’ parameters

There’s no magical Python feature to handle cooperation among classes with divergent __init__() parameters. Consequently, this requires some care to design our class parameter lists. The cooperative multiple inheritance approach is to accept keyword arguments for any parameters that are not required by every subclass implementation. A method must pass the unexpected arguments on to its super() call, in case they are necessary to later methods in the MRO sequence of classes.

Python’s function parameter syntax provides a tool we can use to do this, but it makes the overall code look cumbersome. Have a look at a version of the Friend multiple inheritance code:

Get hands-on with 1200+ tech skills courses.