I am instantiating a class A (which I am importing from somebody else, so I can’t modify it) into my class X.
Is there a way I can intercept or wrap calls to methods in A? I.e., in the code below can I call
x.a.p1()
and get the output
X.pre A.p1 X.post
Many TIA!
class A: # in my real application, this is an imported class # that I cannot modify def p1(self): print 'A.p1' class X: def __init__(self): self.a=A() def pre(self): print 'X.pre' def post(self): print 'X.post' x=X() x.a.p1()
Here is the solution I and my colleagues came up with:
Gives:
So when creating an instance of your object, wrap it with the PrePostCaller object. After that you continue using the object as if it was an instance of the wrapped object. With this solution you can do the wrapping on a per instance basis.