Q1. What is a decorator in Python?
A decorator is a function that takes another function and extends its behavior without explicitly modifying it. It's used with the @ syntax. Example:
def my_decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@my_decorator
def say_hello():
print("Hello")Q2. How do you create a decorator with arguments?
Create a decorator factory that returns a decorator. Example:
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello {name}")Q3. What is the difference between a decorator and a wrapper?
A decorator is a function that returns a wrapper function. The wrapper is the inner function that actually adds behavior. The decorator is just the syntactic sugar for applying the wrapper to the target function.
Q4. What is the functools.wraps decorator used for?
functools.wraps is used to preserve the metadata (__name__, __doc__, etc.) of the original function when using decorators. Without it, the wrapper function loses the original's identity. Example:
from functools import wraps
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapperQ5. Can decorators be applied to classes?
Yes, decorators can be applied to classes to modify their behavior (like adding methods or properties) or to wrap the class itself. Class decorators receive the class as argument and return a modified class.
