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!
By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.
Decorator Method is a Structural Design Pattern which allows you to dynamically attach new behaviors to objects without changing their implementation by placing these objects inside the wrapper objects that contains the behaviors.
In Python, the @classmethod decorator is used to declare a method in the class as a class method that can be called using ClassName. MethodName() . The class method can also be called using an object of the class. The @classmethod is an alternative of the classmethod() function.
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:
def wrapper(func):
def wrapped():
print 'Enter'
result = func()
print 'Exit'
return result
return wrapped
And here is an example of how you could use this:
>>> def say_hello():
... print 'Hello'
...
>>> say_hello() # behavior before wrapping
Hello
>>> say_hello = wrapper(say_hello)
>>> say_hello() # behavior after wrapping
Enter
Hello
Exit
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:
>>> @wrapper
... def say_hello():
... print 'Hello'
...
>>> say_hello()
Enter
Hello
Exit
Why would you want to pass the definition for a method through another method?
Because you want to modify its behavior.
And how would that even work?
Perfectly, since functions are first-class in Python.
def decorator(f):
def wrapper(*args, **kwargs):
print 'Before!'
res = f(*args, **kwargs)
print 'After!'
return res
return wrapper
def somemethod():
print 'During...'
somemethod = decorator(somemethod)
somemethod()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With