When Is The Python Decorator Used? 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 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")