Python - Higher Order Functions

Function as a Data

Example

def greet():
    return 'Hello Everyone!'
print(greet())
wish = greet        # 'greet' function assigned to variable 'wish'
print(type(wish))   
print(wish())      

Output

Hello Everyone!
<type 'function'>
Hello Everyone!

Function as an Argument


Example

def add(x, y):
    return x + y
def sub(x, y):
   return x - y
def prod(x, y):
    return x * y
def do(func, x, y):
   return func(x, y)
print(do(add, 12, 4))  # 'add' as arg
print(do(sub, 12, 4))  # 'sub' as arg
print(do(prod, 12, 4))  # 'prod' as arg

Output

16
8
48

Returning a Function


Example 1

def outer():
    def inner():
        s = 'Hello world!'
        return s            
    return inner()    
print(outer())

Output

Hello world!


Example 2

def outer():
    def inner():
        s = 'Hello world!'
        return s            
    return inner   # Removed '()' to return 'inner' function itself
print(outer()) #returns 'inner' function
func = outer() 
print(type(func))
print(func()) # calling 'inner' function

Output

<function inner at 0xxxxxx>
<type 'function'>
Hello world!

No comments:

Post a Comment