Needed: Real-world examples for Python's Cooperative Multiple Inheritance

Daniel Urban urban.dani at gmail.com
Sun Dec 12 14:10:48 EST 2010


> So far, the only situation I can find where method names necessarily
> overlap is for the basics like __init__(), close(), flush(), and
> save() where multiple parents need to have their own initialization
> and finalization.

One other possibility is subclasses of the JSONEncoder class. For
example the writer of class X provides a class, XJSONEncoder, which is
able to serialize X instances (by extending the default method).
Similarly there is a YJSONEncoder class, which can serialize Y
instances. Those classes implement the default method like this:

def default(self, o):
    if isinstance(o, X):
        ... # serialize the X instance
    else:
        return super().default(o) # let the next in the MRO try to handle it

If YJSONEncoder encodes Y instances similarly, one can create an
encoder class, which can encode both X and Y instances:

class XYJSONEncoder(XJSONEncoder, YJSONEncoder): pass

It is usable this way:
json.dumps([X(), Y()], cls=XYJSONEncoder)


Regards,
Daniel



More information about the Python-list mailing list