Python wrapping method invocations with pre and post methods

This my Answer to the stackoverflow question: Python: wrapping method invocations with pre and post methods:

You could just modify the A instance and replace the p1 function with a wrapper function:

def wrapped(pre, post, f):
    def wrapper(*args, **kwargs):
        pre()
        retval = f(*args, **kwargs)
        post()
        return retval
    return wrapper

class Y:
    def __init__(self):
        self.a=A()
        self.a.p1 = wrapped(self.pre, self.post, self.a.p1)

    def pre(self): print 'X.pre'
    def post(self): print 'X.post'