python/decorator_chaining.py

33 lines
898 B
Python

def decorator_one(func):
def wrapper():
print("Decorator one start")
func()
print("Decorator one end")
return wrapper
def decorator_two(func):
def wrapper():
print("Decorator two start")
func()
print("Decorator two end")
return wrapper
@decorator_one
@decorator_two
def greet():
print("Hello!")
greet()
'''
How it works:
1. The `decorator_one` function is defined, which takes a function `func` as an argument.
2. Inside `decorator_one`, a `wrapper` function is defined that prints messages before and after calling `func`.
3. The `wrapper` function is returned from `decorator_one`.
4. The `decorator_two` function is defined in a similar way.
5. The `greet` function is decorated with both `@decorator_one` and `@decorator_two`.
6. When `greet` is called, it goes through both decorators, printing messages from each.
'''