Middle+
Tell about 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 behavior, without modifying the original code of the decorated function.
They are often used for:
- Logging function calls
- Access control checks
- Caching results
- Measuring execution time
Example of a simple decorator:
def decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling function {func.__name__}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} finished")
return result
return wrapper
@decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("World")
Here, @decorator is syntactic sugar for say_hello = decorator(say_hello).
Decorators can be parameterized, accept arguments, and be applied to class methods. They help write cleaner and more reusable code, separating additional logic from the main function.