(13)DECORATORS:
A decorator is a function that takes another function as an argument that extends the behavior of this function without explicitly modifying it.
It allows you to add new functionality to an existing function. There are two types of decorators class decorators and function decorators first function decorator.
1.Function decorator:
for example:
def start_end_decorator(func):
def wrapper():
print('Start')
func()
print('End')
return wrapper
def print_name():
print('Alex')
print_name()
print()
# Now wrap the function by passing it as argument to the decorator function
# and asign it to itself -> Our function has extended behaviour!
print_name = start_end_decorator(print_name)
print_name()
output =
Alex
Start
Alex
End
To print sum with help of the decorators.
for example:
def start_end_decorator_3(func):
def wrapper(*args, **kwargs):
print('Start')
result = func(*args, **kwargs)
print('End')
return result
return wrapper
@start_end_decorator_3
def add_5(x):
return x + 5
result = add_5(10)
print(result)
output =
Start
End
15
To identify the function.
for example:
def start_end_decorator_3(func):
def wrapper(*args, **kwargs):
print('Start')
result = func(*args, **kwargs)
print('End')
return result
return wrapper
@start_end_decorator_3
def add5(x):
return x + 5
print(help(add5))
print(add5.__name__)
output = Help on function wrapper in module __main__:
wrapper(*args, **kwargs)
None
wrapper
To print a sentence multiple times.
for example:
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Do something before
result = func(*args, **kwargs)
# Do something after
return result
return wrapper
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('Alex')
output =
Hello Alex
Hello Alex
Hello Alex
2.Class decorator:
for exmple:
import functools
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.num_calls = 0
# extend functionality, execute function, and return the result
def __call__(self, *args, **kwargs):
self.num_calls += 1
print(f"Call {self.num_calls} of {self.func.__name__!r}")
return self.func(*args, **kwargs)
@CountCalls
def say_hello(num):
print("Hello!")
say_hello(5)
say_hello(5)
output =
Call 1 of 'say_hello'
Hello!
Call 2 of 'say_hello'
Hello!
Comments
Post a Comment
If you have any doubts please let me know