Let's say I have an existing python 2.7 class:
class TestClass(object):
def foo1(self):
return self.foo2()
def foo2(self):
return self.foo3()
def foo3(self):
return 'Hello World!'
Is there a way during runtime to dynamically add (monkey patch) a decorator (@testdecorator) to each of the three existing methods, foo1, foo2, and foo3?
Thank you in advance for any suggestions!
That sounds like a horrible thing to do, but it's perfectly possible. @decorator
is just syntactic sugar; you can do it the long way:
TestClass.foo1 = testdecorator(TestClass.foo1)
Yes:
TestClass.foo1 = testdecorator(TestClass.foo1)
And so on.
If you want to patch it on specific instances rather than on the class, that is doable too, although it's a little more work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.