Coding an extendable class

Jeff Epler jepler at unpythonic.net
Tue Dec 30 23:08:10 CET 2003


Python sometimes uses "mixin" classes -- see the SocketServer module for
one example in a core module.

So main.Graph would be the real graph class, and
graphtools.hamilton.HamiltonMixin would be one mixin:
    class MyGraph(main.Graph, hamilton.HamiltonMixin):
        pass
You could use new.classobj to create a class object with a given list
of mixins at runtime (untested):
    # In Main
    _graph_classes = []
    
    def add_mixin(m):
        _graph_classes.append(m)
        global Graph
        Graph = new.classobj("Graph", _graph_classes, {})

    add_mixin(main._Graph)

    # In each module that defines a new mixin
    class HamiltonianMixin:
        pass
    main.add_mixin(HamiltonianMixin)
however, having the exact nature of main.Graph depend on what other
modules have been imported is not what most Python users would expect.
I prefer the solution of having the user list mixins by creating a
"personalized" graph class.

Jeff





More information about the Python-list mailing list