Write a python program to illustrate the working of decorators


The use of a decorator in Python. A decorator is a function that wraps another function to add functionality to it. In this code, you have defined a decorator function my_decorator, which wraps the msg function. Here's a breakdown of the code:

  • def my_decorator(func): This is the decorator function. It takes a function func as an argument and defines an inner function called wrapper. The wrapper function adds some behavior before and after calling func.
  • def wrapper(): This is the inner function within the decorator. It adds behavior before and after calling the original function func.
  • Inside the wrapper function, there are print statements to indicate that something is happening before and after the original function is called.
  • return wrapper: The decorator function returns the wrapper function.
  • @my_decorator: This is a decorator syntax, indicating that the msg function is decorated with my_decorator. It means that when you call msg, it will be wrapped by the wrapper function defined in my_decorator.
  • def msg(): This is the function to be decorated. It simply prints "Hello world!".
  • When you call msg(), it is actually calling the decorated function. The my_decorator wraps msg, so it prints the additional messages before and after "Hello world!" is printed.

The msg function is decorated with my_decorator, so when you call msg(), it prints "Something is happening before the function is called," then "Hello world!", and finally "Something is happening after the function is called." This demonstrates how decorators can add behavior to functions without modifying their source code.


Source Code

# Decorator function
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called")
        func()
        print("Something is happening after the function is called")
    return wrapper
 
# Function to be decorated
@my_decorator
def msg():
    print("Hello world !")
 
# Call the decorated function
msg()

Output

Something is happening before the function is called
Hello world !
Something is happening after the function is called

Example Programs