Decorators in python

Decorators: 

Before knowing about the decorators we should have basic knowledge about the functions.

Python’s functions are first-class objects. You can assign them to variables, store them in data structures, pass them as arguments to other functions, and even return them as values from other functions.

A decorator is a function that receives another function as argument. The behaviour of the argument function is extended by the decorator without actually modifying it.
def calculate_decorator(function_parameter): #receives another function as argument

def warp_calculation(cal_num): # wrap the function and extends its behaviour

add = function_parameter(cal_num) + 4
print(add)

return warp_calculation # return wrapped function

def calculation(number):

return number # return number

calculation = calculate_decorator(calculation)
calculation(3)
Output:

    
(or another way as follow)

@[decorator_function_name] syntax to specify a decorator function
def calculate_decorator(function_parameter): #receives another function as argument

def warp_calculation(cal_num): # wrap the function and extends its behaviour

add = function_parameter(cal_num) + 4
print(add)

return warp_calculation # return wrapped function

@calculate_decorator
def calculation(number):

return number # return number

calculation(3)
Output

Comments

Popular posts from this blog

Switch frame in selenium python

Learn basics of python collection data type (list, tuple, dictionary and set) instantly

Python property method