Can someone thoroughly explain the last line of the following code:
def myMethod(self):
# do something
myMethod = transformMethod(myMethod)
Why would you want to pass the definition for a method through another method? And how would that even work? Thanks in advance!
This is an example of function wrapping, which is when you have a function that accepts a function as an argument, and returns a new function that modifies the behavior of the original function.
Here is an example of how this might be used, this is a simple wrapper which just prints ‘Enter’ and ‘Exit’ on each call:
And here is an example of how you could use this:
For convenience, Python provides the decorator syntax which is just a shorthand version of function wrapping that does the same thing at function definition time, here is how this can be used: