Home>Article>Backend Development> How to create higher-order functions in Python?
In Python, a function that takes another function as a parameter or returns a function as output is called a higher-order function. Let's take a look at its features -
This function can be stored in a variable.
This function can be passed as a parameter to another function.
Higher-order functions can be stored in lists, hash tables, etc.
Functions can be returned from functions.
Let’s look at some examples −
In this example, these functions are treated as objects. Here, the function demo() is assigned to a variable -
# Creating a function def demo(mystr): return mystr.swapcase() # swapping the case print(demo('Thisisit!')) sample = demo print(sample('Hello'))
tHISISIT! hELLO
Passed as a parameter in this function.demo3()The function calls thedemo()anddemo2()functions as parameters.
def demo(text): return text.swapcase() def demo2(text): return text.capitalize() def demo3(func): res = func("This is it!") # Function passed as an argument print (res) # Calling demo3(demo) demo3(demo2)
tHIS IS IT! This is it!
Now, let’s discuss decorators. We can use decorators as higher order functions.
In a decorator, a function is passed as a parameter to another function and then called in the wrapping function. Let’s look at a quick example −
@mydecorator def hello_decorator(): print("This is sample text.")
The above can also be written as -
def demo_decorator(): print("This is sample text.") hello_decorator = mydecorator (demo_decorator)
In this example, we will work with decorators as higher-order functions -
def demoFunc(x,y): print("Sum = ",x+y) # outer function def outerFunc(sample): def innerFunc(x,y): # inner function return sample(x,y) return innerFunc # calling demoFunc2 = outerFunc(demoFunc) demoFunc2(10, 20)
Sum = 30The Chinese translation of
def demoFunc(x,y): print("Sum = ",x+y) # outer function def outerFunc(sample): def innerFunc(x,y): # inner function return sample(x,y) return innerFunc # calling demoFunc2 = outerFunc(demoFunc) demoFunc2(10, 20)
Sum = 30
The above example can be simplified using a decorator with @symbol. The application of decorators can be simplified by placing the @ symbol before the function we want to decorate -
# outer function def outerFunc(sample): def innerFunc(x,y): # inner function return sample(x,y) return innerFunc @outerFunc def demoFunc(x,y): print("Sum = ",x+y) demoFunc(10,20)
Sum = 30
The above is the detailed content of How to create higher-order functions in Python?. For more information, please follow other related articles on the PHP Chinese website!