Q3: What are decorators in Python, and how do they enhance the functionality of functions in the language?
A3:
Decorators in Python are a powerful feature that allows the modification or extension of the behavior of functions or methods. They are denoted by the @decorator syntax and are applied to functions to alter their functionality. Decorators are essentially higher-order functions that take a function as input and return a new function with enhanced or modified behavior.
Here's an example of a simple decorator:
pythondef 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, my_decorator is a decorator that wraps the say_hello function, adding behavior before and after its execution.
ไม่มีความคิดเห็น:
แสดงความคิดเห็น