Decorators in Python
Decorators are a way to modify the behavior of a function without changing its code. Here's an example of defining a simple decorator:
python
def my_decorator(func):
def wrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello, world!")
In this example, we define a decorator function called my_decorator. The decorator function takes a function as its argument, and returns a new function called wrapper that modifies the behavior of the original function. We then use the @my_decorator syntax to apply the decorator to the say_hello function.
When we call the say_hello function, the decorator will add some additional behavior before and after the original function is called:
python
say_hello() # prints "Before the function is called.", "Hello, world!", "After the function is called."
No comments:
Post a Comment