define decorator in python code example
Example 1: decorator python
def our_decorator(func):
def function_wrapper(x):
print("Before calling " + func.__name__)
func(x)
print("After calling " + func.__name__)
return function_wrapper
@our_decorator
def foo(x):
print("Hi, foo has been called with " + str(x))
foo("Hi")
Example 2: 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 3: python decorator
def logging(f):
def decorator_function(*args, **kwargs):
print('executing '+f.__name__)
return f(*args, **kwargs)
return decorator_function
@logging
def hello_world():
print('Hello World')