Q12: What are Python decorators and how do they contribute to code modularity and reusability? Provide an example to illustrate their usage.
A12:
Python Decorators:
- Decorators in Python are functions that are used to modify or extend the behavior of other functions or methods. They provide a way to wrap a function with additional functionality, enhancing code modularity and reusability.
Code Modularity and Reusability:
- Decorators allow developers to separate concerns and apply reusable behavior to multiple functions without modifying their code directly. This promotes cleaner code, as common functionality can be abstracted into decorators.
python# Example of a simple decorator
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!")
# Calling the decorated function
say_hello()In this example, the
my_decoratorfunction is a decorator that adds behavior before and after thesay_hellofunction is called. The@my_decoratorsyntax is a convenient way to apply the decorator to thesay_hellofunction.