super() and automatic method combination

Paul Rubin http
Wed May 18 08:25:28 EDT 2005


I'm trying the super() function as described in Python Cookbook, 1st ed,
p. 172 (Recipe 5.4).

    class A(object):
        def f(self):
                print 'A'


    class B(object):
        def f(self):
                print 'b'


    class C(A,B):
        def f(self):
                super(c,self).f()
                print 'C'

    def test(cls):
       x = cls()
       x.f()

    test(C)

I have the impression that this is supposed to call the f method
in both A and B, so it should print
   A
   B
   C
or maybe
  B
  A
  C
depending on the resolution order.  However, it only calls A.f and not B.f.

I also notice that if I say


    class B(object):
        def f(self):
            super(B,self).f()
            print 'b'

then 
  test(B)
raises an exception since B has no superclass with an f method.  That
doesn't seem like such a good thing necessarily.

Anyway, is there a preferred way of writing this example so that C.f
automatically calls both A.f and B.f?

It would be nice to make some decorators to do CLOS-like automatic
method combination, something like:

   class C(A,B):
     @aftermethod
     def f(self):
       print 'C'

   test(C)

would call A.f and B.f and then call C.f.

   class C(A,B):
     @beforemethod
     def f(self):
       print 'C'

   test(C)

would call C.f and then call A.f and B.f.  This would not be exactly
the same as calling super, since it should not be an error to call a
beforemethod or aftermethod when the superclass doesn't have its own
method for that operation.  (I'm not sure how CLOS does this.  I've
played with Flavors (a forerunner of CLOS) but have never actually
used CLOS).



More information about the Python-list mailing list