Categories

Dec 19, 2019 in Python

Q: What Are Decorators In Python?

1 Answer

Dec 19, 2019
Python decorator gives us the ability to add new behavior to the given objects dynamically. In the example below, we’ve written a simple example to display a message pre and post the execution of a function.

def decorator_sample(func):

    def decorator_hook(*args, **kwargs):

        print("Before the function call")

        result = func(*args, **kwargs)

        print("After the function call")

        return result

    return decorator_hook

@decorator_sample

def product(x, y):

    "Function to multiply two numbers."

    return x * y

print(product(3, 3))

The output is:

Before the function call

After the function call

9
Click here to read more about Python
Click here to read more about Insurance

Related questions

Madanswer
Aug 30 in Python
Jun 30 in Python
Jun 12 in Python
...