How to Answer Python Decorators Question Quickly

Here are the three points to tell if someone asks about the decorator concept in python. If required, you can byheart these.

ON THIS PAGE

  1. Python decorators
  2. Decorator principle
  3. Decorator best example

Python decorators

Point:1

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

Point:2

They accept a function as an argument, and it creates a new function. This concept is also called function pointers in python.

Point:3

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

Decorator principle

Python Decorators

Decorator best example

Here’s a way to write a decorator in python. A function f has passed to the hello function. Inside of that added a wrapper function that adds functionality for the f function.

#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 of decorator

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

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.