fbpx

Can you explain the purpose and benefits of using decorators in Python? Provide an example of a decorator you have implemented or used.

Decorators in Python are a powerful way to modify or enhance the behavior of functions or classes without changing their source code. They are often used for tasks like logging, memoization, and access control. Here's an example of a simple decorator that logs function calls:

def log_function_call(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function: {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_function_call
def my_function():
    print("This is my function.")

my_function()

 

# Dream job to realty