Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
669 views
Welcome To Ask or Share your Answers For Others

1 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...