Puzzling OO design problem

El Pitonero pitonero at gmail.com
Sat Apr 9 13:39:48 EDT 2005


It may be useful to separate the code into version-independent part and
version-dependent part. Also, one can try to implement the higher-level
logic directly in the class definition of A, B, etc., and then use the
version objects only as patches for the details. That is, one can use
place-holder calls. The place-holder calls do nothing if a feature is
not really implemented (either in a parent class, or in an older
version).

class World(object):

    def __init__(w, version):

        class A(object):
            def ff(): pass # place holder for version-dependent code
            def f(self): # version-independent code
                return self.ff()

        class B(A):
            def gg(): pass
            def g(self):
                return self.gg()

        for cls in (A, B):
            setattr(w, cls.__name__, w.versionize(cls, version))

    def versionize(w, cls, version):
        import inspect
        methods = inspect.getmembers(version, inspect.ismethod)
        methods = [m[1] for m in methods if m[0].split('_')[0] ==
cls.__name__]
        for m in methods:
            m_name = '_'.join(m.__name__.split('_')[1:])
            import new
            im = new.instancemethod(m.im_func, None, cls)
            setattr(cls, m_name, im)
        return cls

class Version1(object):
    def A_ff(self):
        return 'A.ff: version 1'
    def B_gg(self):
        return 'B.gg: version 1'

class Version2(Version1):
    def A_ff(self):
        return 'A.ff: version 2'
    def B_ff(self):
        return 'B.ff: version 2'

w1, w2 = World(Version1), World(Version2)
a1, b1 = w1.A(), w1.B()
a2, b2 = w2.A(), w2.B()

print a1.f() # prints 'A.ff: version 1'
print b1.f() # prints 'A.ff: version 1'
print b1.g() # prints 'B.gg: version 1'
print '------------'
print a2.f() # prints 'A.ff: version 2'
print b2.f() # prints 'B.ff: version 2'
print b2.g() # prints 'B.gg: version 1'




More information about the Python-list mailing list