David Wolever David Wolever - 1 day ago 5
Python Question

Python: Correct way to initialize when superclasses accept different arguments?

If I've got three classes like this:

class BaseClass(object):
def __init__(self, base_arg, base_arg2=None):
...

class MixinClass(object):
def __init__(self, mixin_arg):
...

class ChildClass(BaseClass, MixinClass):
def __init__(self, base_arg, mixin_arg, base_arg2=None):
???


What is the correct way to initialize
MixinClass
and
BaseClass
?

It doesn't look like I can use
super
because the
MixinClass
and the
BaseClass
both accept different arguments… And two calls,
MixinClass.__init__(...)
and
BaseClass.__init__(...)
, will could cause the diamond inheritence problem
super
is designed to prevent.

Answer

Basically, in Python, you can't support this type of inheritance safely. Luckily you almost never need to, since most methods don't care what something is, only that it supports a particular interface. Your best bet is to use composition or aggregation: have your class inherit from one of the parent classes, and contain a reference to an instance of the second class. As long as your class supports the interface of the second class (and forwards messages to the contained instance) this will probably work out fine.

In the above example (where both classes inherit from object) you can (probably) safely just inherit from both classes and call both constructors using MixinClass.__init__ and BaseClass.__init__. But note that's not safe to do if the parent classes call super in their constructors. A good rule of thumb is to use super if the parent classes use super, and __init__ if the parent classes use __init__, and hope you're never trapped having to inherit from two classes which chose different methods for initialization.

Comments