execute a function before and after any method of a parent class

Aaron "Castironpi" Brady castironpi at gmail.com
Fri Oct 3 19:45:11 CEST 2008

On Oct 3, 9:03 am, TP <Tribulati... at Paralleles.invalid> wrote:
> Hi everybody,
> I would like to be able to specialize an existing class A, so as to obtain a
> class B(A), with all methods of B being the methods of A preceded by a
> special method of B called _before_any_method_of_A( self ), and followed by
> a special method of B called _after_any_method_of_A( self ).
> The goal is to avoid to redefine explicitly in B all methods of A.
> Is this possible in Python?
> Thanks a lot
> Julien
> --
> python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
> (55l4('])"
> "When a distinguished but elderly scientist states that something is
> possible, he is almost certainly right. When he states that something is
> impossible, he is very probably wrong." (first law of AC Clarke)

Yes it's possible.  The exact solution depends on how much control you
want, and over what.  Do you want inheritance or delegation?  Do you
want the same pre and post method for all inherited methods?  Will you
always use single-inheritance?  Would you mind using a list of names,
as a sort of midpoint between complete redefinition and completely
dynamic?  Do you want class lookups to succeed?  If so, what do you
want them to do?

Generally, you could build the class dynamically with a metaclass, or
use __getattr__ a lookup.

More information about the Python-list mailing list