Multiple inheritance: Interface problem workaround, please comment this

Michele Simionato michele.simionato at gmail.com
Fri Apr 8 08:38:33 EDT 2005


Axel:

> So, if there are ready class-modules, and I want to use them for
> multiple inheritance, I've to rewrite the init's of classes in the
> module!

Or you use a metaclass that rewrites the __init___ method for you.

This is a start (warning: written in 5 minutes and not tested more than
you see):

"""Given a hierarchy, makes __init__ cooperative.
The only change needed is to add a line

    __metaclass__ = CooperativeInit

to the base class of you hierarchy."""

from decorate import decorate # see today thread on decorators for this

def make_cooperative_init(cls, name, bases, dic):

    def call_cooperatively(__init__, self, *args, **kw):
        super(cls, self).__init__(*args, **kw)
        __init__(self, *args, **kw)

    __init__ = cls.__dict__.get("__init__")
    if __init__:
        cls.__init__ = decorate(__init__, call_cooperatively)

class CooperativeInit(type):
    __init__ = make_cooperative_init

class Base:
    __metaclass__ = CooperativeInit
    def __init__(self):
        print "B.__init__"

class C1(Base):
    def __init__(self):
        print "C1.__init__"

class C2(Base):
    def __init__(self):
        print "C2.__init__"

class D(C1, C2):
    def __init__(self):
        print "D.__init__"




D()

# you get
# B.__init__
# C2.__init__
# C1.__init__
# D.__init__


                  Michele Simionato




More information about the Python-list mailing list