Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Decorators in python

In this chapter, you will learn about decorators in python with examples. The decorator allows you to decorate a function. Let’s see the definition and write some code snippets to understand the decorator in python.

Decorators:

  1. A decorator is similar to a design pattern that helps in adding new functionality to an existing object without modifying its structure.
  2. Decorator concept can also be called metaprogramming which is the part of a program that modifies another part of a program during the execution.
  3. Decorator creates a brand new function that contains the old code, and then add new code to that
  4. They use the @ operator and are then placed on top of the original function

Let’s write a simple program which greets an employee

def greetEmployee():
    print('Hi, good morning')

del greetEmployee

greetEmployee()

# output
# Traceback (most recent call last):
#   File "deco.py", line 7, in <module>
#     greetEmployee()
# NameError: name 'greetEmployee' is not defined

As we can see in the above code snippet, it throwing an error, as we have deleted the function. Now modify the above code snippet

def greetEmployee():
    print('Hi, good morning')

copyGreetEmploye = greetEmployee
del greetEmployee

copyGreetEmploye()

# output
# Hi, good morning

As we can see in the above code snippet, we have copied the greetEmployee() function to the variable copyGreetEmploye, and copyGreetEmploye prints the message.

The above code snippets will help you to understand the decorator concept properly, so that was the intention to create those functions. Now let’s create a decorator function.

def calculator_decorator(operation):
    print('Initiliazing the calculator...')
    def perform_operation():
        print('Performing the operation...')
        operation()
    return perform_operation



@calculator_decorator
def add_two_number():
    result = 2+2
    print('Adding the number 2 + 2 ')
    print('Result = {result}'.format(result=result))

add_two_number()

# output
# Initiliazing the calculator...
# Performing the operation...
# Adding the number 2 + 2 
# Result = 4

 

Decorators in python code snippet

One thought on “Decorators in python

Comments are closed.