What is a Python Decorator?

What is a Python Decorator?

a) A function that modifies the behavior of another function or method
b) A tool used to generate random numbers
c) A function that returns multiple values
d) A method for creating new classes

Answer:

a) A function that modifies the behavior of another function or method

Explanation:

A Python decorator is a function that wraps another function or method, modifying its behavior or adding additional functionality. Decorators are often used to enhance or extend the behavior of existing functions in a reusable and concise way.

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

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

In this example, @my_decorator is a decorator that wraps the say_hello() function, adding additional behavior before and after the original function is executed.

Decorators are widely used in Python to implement cross-cutting concerns like logging, authorization, and caching, making them a powerful tool for improving code modularity and reusability.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top