Higher Order Functions
Higher Order Functions
result = higher_order_function('square')
print(result(3)) #9
result = higher_order_function('cube')
print(result(3)) # 27
result = higher_order_function('absolute')
print(result(-3)) # 3
Python Closures
closure_result = add_ten()
print(closure_result(5)) # 15
print(closure_result(10)) # 20
Decorators in Python
return func(a, b)
return inner
@smart_divide
def divide(a, b):
print(a/b)
def decorator_list(fnc):
def inner(list_of_tuples):
return [fnc(val[0], val[1]) for val in
list_of_tuples]
return inner
@decorator_list
def add_together(a, b):
return a + b
print(add_together([(1, 3), (3, 17), (5, 5), (6, 7)]))
Applying Multiple Decorators to a Single Function
'''These decorator functions are higher order functions
that take functions as parameters'''
# First Decorator
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = func.upper()
return make_uppercase
return wrapper
# Second decorator
def split_string_decorator(function):
def wrapper():
func = function()
splitted_string = func.split()
return splitted_string
return wrapper
@split_string_decorator
@uppercase_decorator # order with decorators is important in this case - .upper() function does not work with lists
def greeting():
return 'Welcome to Python'
print(greeting()) # WELCOME TO PYTHON
Accepting Parameters in Decorator Functions
def decorator_with_parameters(function):
def wrapper_accepting_parameters(para1, para2, para3):
function(para1, para2, para3)
print("I live in {}".format(para3))
return wrapper_accepting_parameters
@decorator_with_parameters
def print_full_name(first_name, last_name, country):
print("I am {} {}. I love to teach.".format(
first_name, last_name, country))
print_full_name("Robert", "Downey",'Finland')
Built-in Higher Order Functions
Example:1
numbers = [1, 2, 3, 4, 5] # iterable
def square(x):
return x ** 2
numbers_squared = map(square, numbers)
print(list(numbers_squared)) # [1, 4, 9, 16, 25]
# Lets apply it with a lambda function
numbers_squared = map(lambda x : x ** 2, numbers)
print(list(numbers_squared)) # [1, 4, 9, 16, 25]
Example:2
numbers_str = ['1', '2', '3', '4', '5'] # iterable
numbers_int = map(int, numbers_str)
print(list(numbers_int)) # [1, 2, 3, 4, 5]
Example:3
names = ['Robert', 'Lidiya', 'Ermias', 'Abraham'] # iterable
def change_to_upper(name):
return name.upper()
def is_even(num):
if num % 2 == 0:
return True
return False
def is_odd(num):
if num % 2 != 0:
return True
return False