Decorators in Python

 

Concept


In Python, functions are the first class objects, which means that –

  • Functions are objects; they can be referenced to, passed to a variable and returned from other functions as well.
  • Functions can be defined inside another function and can also be passed as argument to another function.
  • powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it.

    In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.



Code Example


''' Creating Decorator 1 '''

def uppercase_decorator(function):
      def wrapper():
            make_uppercase = function().upper()
            return make_uppercase

    return wrapper

 

''' Creating Decorator 2 '''

def split_string(function):
      def wrapper():
            splitted_string = function().split()
            return splitted_string

    return wrapper

 

So now we have two way to call Decorator

Way1:

def say_hi():
    return 'hello there'

decorate = uppercase_decorator(say_hi)
print(decorate())

 

Output: HELLO THERE

 

Way2:

@split_string
@uppercase_decorator
def say_hi():
      return 'hello there'

decorate = say_hi()
print(decorate())

 

Output: ['HELLO', 'THERE']

 

Note**: 

First @uppercase_decorator this will be exected and the Output of the first decorator will come to the second decorator @split_string than @split_string this will be executed


Screenshot :



Quiz Level 1

Quiz Level 2


Request Me

Comments

Popular posts from this blog

How To Create .ENV File in Python

Create a Large file for Test Data Processing using Python

How to solve the Liner Equation using Python