Python : What are decorators in python programming.

 

Decorators in python is the process of adding functionality to an existing function in Python without changing the structure of the function itself. 

Example: Here the function say_hello_world is added with additional print statements without changing its Orginal code. This is achieved by passing the entire say_hello_world function as a argument for my_decorator function.

Code: 

def my_decorator(func):
    def wrapper():
        print("Before the function is called")
        func()
        print("After the function is called")
    return wrapper

def say_hello_world():
    print("Hello World!")
x = my_decorator(say_hello_world)
x()

Output:



List of predefined decorators are given below,


Comments