when to use decorators python code example
Example 1: python decorators
import time
def delay_decorator(function):
def wrapper_function():
print("-----------------------I am gonna greet you--------------------------")
time.sleep(2)
function()
time.sleep(1)
print("------------------How do you feel about that greet?-------------------")
return wrapper_function
@delay_decorator
def greet():
print("Helllllloooooooooo")
greet()
Example 2: decorators in python
'pass function which we want to decorate in decorator callable object'
def our_decorator(func):
def wrapper(x):
if x%2==0:
return func(x)
else:
raise Exception("number should be even")
return wrapper
@ our_decorator
def func(x):
print(x,"is even")
func(2)
func(1)
' if you do not want to use @'
func=our_decorator(func)
func(2)