Python Decorators

In Python, a decorator is a function that takes another function as input, adds some functionality to it, and returns the new function. A decorator is used to modify or extend the behavior of a function or class without changing its source code.

Here is an example of a decorator in Python:

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

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

say_hello()
Source‮figi.www:‬tidea.com

In this example, we define a decorator my_decorator that takes a function func as input and returns a new function wrapper. Inside wrapper, we add some extra functionality before and after calling func.

We then define a function say_hello and decorate it using the @my_decorator syntax. This tells Python to apply the my_decorator function to the say_hello function. When we call say_hello(), the output will be:

Before the function is called.
Hello!
After the function is called.

The decorator my_decorator adds extra functionality to the say_hello function without modifying its source code. We can use decorators to add logging, caching, authentication, or other functionality to our functions or classes without changing their behavior.

Decorators can also be used with classes and class methods, and they can take arguments to customize their behavior. Decorators can be chained together, and multiple decorators can be applied to the same function or class.