super() and automatic method combination

Steven Bethard steven.bethard at gmail.com
Wed May 18 11:39:04 EDT 2005


Paul Rubin wrote:
> 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)

You want a super object that doesn't raise an exception if the 
superclass doesn't have a particular function.  Try sopmething like:

py> class mysuper(super):
...     def __getattribute__(self, name):
...         try:
...             return super(mysuper, self).__getattribute__(name)
...         except AttributeError:
...             def null(*args, **kwargs):
...                 pass
...             return null
...
py> class A(object):
...     def f(self):
...          mysuper(A, self).f()
...          print 'A'
...
py> class B(object):
...     def f(self):
...          mysuper(B, self).f()
...          print 'B'
...
py> class C(A, B):
...     def f(self):
...          mysuper(C, self).f()
...          print 'C'
...
py> C().f()
B
A
C

I haven't been careful here to only replace functions with functions. 
That is, I probably should make a real Null object that acts both like 
the null function above and like the None object otherwise.  But as long 
as you're only using mysuper to get functions, this should work ok. 
Personally, I would probably do what others have suggested and add a 
base class with an f method from which A and B derive, but if that's not 
an option, you can play around with subclassing super and probably get 
something like what you want.

STeVe



More information about the Python-list mailing list