Junior — Middle
What is the role and application of decorators in Python?
sobes.tech AI
Answer from AI
Decorators in Python are functions that take another function and return a new function with extended or modified behavior. They allow adding functionality to functions or methods without changing their original code.
Applications:
- Logging function calls.
- Access control.
- Caching results.
- Measuring execution time.
Example of a simple decorator:
def decorator(func):
def wrapper(*args, **kwargs):
print("Before calling the function")
result = func(*args, **kwargs)
print("After calling the function")
return result
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()