Middle
What is a decorator in Python?
sobes.tech AI
Answer from AI
A decorator in Python is a function that takes another function and returns a new function with extended or modified behavior, without changing the original code of the decorated function.
Example of using a 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(name):
print(f"Hello, {name}!")
say_hello("World")
Output:
Before calling the function
Hello, World!
After calling the function
Decorators are often used for logging, access control, measuring execution time, and other aspects not related to the main logic of the function.