views:

54

answers:

1

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.

+1  A: 

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.

Chris B.