The decorator is a wrapper that adds extra features to the original function.

ON THIS PAGE

  1. Python decorators
  2. Principle of decorator
  3. Decorator example

Python decorators

Point:1

A decorator is a wrapper around a function. It adds new abilities to the original function.

Point:2

Decorators accept the original function as an argument. This concept is also called function pointers in Python.

Point:3

Decorators do not change the original function. These wrap the existing ones.

Principle of decorator

Python Decorators

Decorator example

A function f has been passed to the hello function. Inside of that added a wrapper function that adds additional functionality for the f function. Here f is the original function, and hello is the wrapper function.

The special syntax @hello, adds the wrapper’s functionality.

#Decorator
def hello(f):
    def wrapper(name):
        print("Hello ",end='' )
        f(name)
    return wrapper

@hello
def print_name(name):
    print(name)
 
print_name("XYZ")

Output

The output of the original function is XYZ. The decorator added the additional functionality of Hello to XYZ.

Hello XYZ

** Process exited - Return Code: 0 **
Press Enter to exit terminal

Related