what is a decorator 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: 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)
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')
Example 4: python decorator
import functools
def repeat(num_times):
def decorator_repeat(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(num_times):
result= func(*args, **kwargs)
return result
return wrapper
return decorator_repeat
@repeat(num_times= 3)
def greet(name):
print(f"Hello {name}")
greet("thomas")