Higher-Order Functions
A higher-order function is a function that operates on other functions, either by taking a function as its argument or by returning a function. We saw this done in last week’s lesson with lambdas, map, filter, and reduce. Decorators are higher-order functions because they take in a function and return a function.
Creating and Applying a Decorator
We’ll need to declare a function that takes in another function as an argument in order to create a decorator. Inside of this decorator, we can then define another function to be returned that will run the function that was passed in as an argument. Let’s see how this is written:
1| # creating and applying our own decorator using the @ symbol 3| def decorator(func):
4| def wrap( ):
5| print("======")
6| func( )
7| print("======")
8| return wrap
10| @decorator 11| def printName( ):
12| print("John!")
14| printName( )
Go ahead and run the cell. We’ll get an output of “John!” with equal signs above and below the name that act as a border. On line 10 we attached our decorator to the printName function. Whenever the printName function is called, the decorator will run, and printName will be passed in as the argument of “func”. Within decorator we declare a function called wrap. This wrap function will print a border, then call the func argument, and then print another border. Remember that decorators must return a function in order to run. Our decorator that we declared can be attached to any function that we write. All functions with this decorator will simply run with a border above and below them.
Decorators with Parameters
Although decorators simply add extra capabilities to functions, they can also have arguments like any other function. Let’s take the following example where we want to run a function x times:
1| # creating a decorator that takes in parameters 3| def run_times(num):
4| def wrap(func):
5| for i in range(num):
6| func( )
7| return wrap
9| @run_times(4) 10| def sayHello( ):
11| print("Hello!")
Go ahead and run the cell. This cell will output “Hello!” four times. The syntax changes when the decorator accepts an argument. Our decorator this time accepted an argument of num, and the wrap function accepted the function as the argument this time. Within our wrap function, we created a for loop that would run the function attached to our decorator as many times as the argument declared on the decorator on line 9.
Note When passing an argument into a decorator, the function is automatically run, so we do not need to call sayhello in this instance.
Do'stlaringiz bilan baham: |