Dispatch with multiple inheritance

looping kadeko at gmail.com
Wed Jul 19 06:22:09 EDT 2006


looping wrote:
> Michael J. Fromberger wrote:
> >
> > Is there a better (i.e., more elegant) way to handle the case marked
> > (**) above?
> >
>
> You have to call super in each method __init__, if you don't, the call
> chain break before the end:
>
> class A (object):
>     def __init__(self):
>         super(A, self).__init__()
>         print "cons A"
>
> class B (object):
>     def __init__(self):
>         super(B, self).__init__()
>         print "cons B"
>
> class C (A):
>     def __init__(self):
>         super(C, self).__init__()
>         print "cons C"
>
> class D (B):
>     def __init__(self):
>         super(D, self).__init__()
>         print "cons D"
>
> class E (C, D):
>     def __init__(self):
>         super(E, self).__init__()  # calls C constructor
>         print "cons E"

After a second tought, it's probably better to call __init__ method
explicitly in class E:

class A (object):
    def __init__(self):
        print "cons A"

class B (object):
    def __init__(self):
        print "cons B"

class C (A):
    def __init__(self):
        super(C, self).__init__()
        print "cons C"

class D (B):
    def __init__(self):
        super(D, self).__init__()
        print "cons D"

class E (C, D):
    def __init__(self):
        D.__init__(self)
        C.__init__(self)
        print "cons E"

this way you have to choose which __init__ from class D or class C is
calling, and which is calling first.
Any Python Guru to give is opinion ?




More information about the Python-list mailing list