Replacing base class

Peter Otten __peter__ at web.de
Wed Mar 3 17:06:03 CET 2004


Alexey Klimkin wrote:

> Assume an example:
> class A:
>   def f(self):
>     print 'A'
> class B(A):
>   def f(self):
>     A.f(self)
>     print 'B'
> class C:
>   def f(self):
>     print 'C'
> 
> I need to make class Bm with the same functionality as B, but
> derived from C, instead of A. Classes C and A have the same
> interface.

Maybe the following pattern could be helpful:

class Abstract(object):
    """ define the interface with noops """
    def f(self):
        pass

class A(Abstract):
    def f(self):
        super(A, self).f()
        print "A",

class B(Abstract):
    def f(self):
        super(B, self).f()
        print "B",

class C(Abstract):
    def f(self):
        super(C, self).f()
        print "C",


You can now make classes that derive from any combination of A, B and C,
where the method f() in each of the bases is invoked exactly once, e. g:

def demo(b):
    print b.__class__.__bases__
    b.f()
    print

for B1 in (A, B, C):
    for B2 in (A, B, C):
        if  B1 != B2:
            class B3(B1, B2):
                pass
            demo(B3())

class B3(A, B, C):
    pass

demo(B3())

The disadvantage is the need of the base class (Abstract in the example)
where the common interface is defined and which seems somewhat unnatural in
Python.

Peter



More information about the Python-list mailing list