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

Almar Klein almar.klein at gmail.com
Fri Oct 3 10:54:04 EDT 2008


Maybe you can use __getattribute__.
I tried it, but got stuck trying to let __getattribute__
work normal without calling itself.

class A(object):
    def foo(self):
        print "hi"

class B(A):
    def __getattribute__(self,name):
        try:
            fun = A.__dict__[name]
        except KeyError:
            fun = None
        if fun and callable(fun):
            self._before_any_method_of_A()
            result =  fun(self)
            self._after_any_method_of_A()
            return result
        else:
            # do some stuff to act normal
            try:
                # erm, this invokes __getattribute__, which will invoke
again,
                # and again, and again...
                return self.__dict__[name]
            except KeyError:
                pass
            try:
                return B.__dict__[name]
            except KeyError:
                pass


    def _before_any_method_of_A(self):
        print "before"

    def _after_any_method_of_A(self):
        print "after"


b = B()
b.foo()


greetings,
  Almar

2008/10/3 TP <Tribulations at paralleles.invalid>

> 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)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081003/c2b55fee/attachment-0001.html>


More information about the Python-list mailing list