Understanding Decorators in Python with Examples
Q: What is a decorator in Python? Can you provide an example of a decorator function?
- Python
- Mid level question
Explore all the latest Python interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Python interview for FREE!
import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"{func.__name__} took {end - start} seconds to execute.") return result return wrapper def my_function(): # some code here pass my_function()
In this example, timer is a decorator function that takes the my_function function as its argument. It defines a new function, wrapper, which takes any number of arguments (*args) and keyword arguments (**kwargs). The wrapper function calls the original function (func(*args, **kwargs)) and calculates the time it takes to execute it. Finally, it prints the elapsed time and returns the result of the original function. The decorator function is applied to the my_function function using the @ symbol to create a new decorated function.


