🐍 Decorators can be complex. But if you study the following, you will understand it in the best form.
Use tutorialspoint to run code online
Step 1: Create Function
Input
def my_function():
print('Step 1: Create first function')
my_function()
Output
Step 1: Create first function
Step 2: Create Decorator
Input
def my_decorator(func):
print('Step 2: Create a decorator. A decorator is a function')
func()
print('Step 3: Call first function')
@my_decorator
def my_function():
print('Step 1: Create first function')
my_function()
Output
Step 2: Create a decorator. A decorator is a function
Step 1: Create first function
Step 3: Call first function
Step 3: Add a function and decorator within the decorator
Input
import functools
def my_decorator(func):
@functools.wraps(func)
def func_that_runs_func():
print('Step 2: Create a decorator. A decorator is a function')
func()
print('Step 3: Call first function')
return func_that_runs_func()
@my_decorator
def my_function():
print('Step 1: Create first function')
my_function()
Output
Step 2: Create a decorator. A decorator is a function
Step 1: Create first function
Step 3: Call first function
Step 3: Passing an argument to a decorator
Input
import functools
def my_decorator_with_argument(num):
def my_decorator(func):
@functools.wraps(func)
def func_that_runs_func(*args, **kwargs):
if num==56:
func()
else:
print(num)
print('Step 3: Call first function')
return func_that_runs_func()
return my_decorator
@my_decorator_with_argument(56)
def my_function():
print('Step 1: Create first function')
my_function()
Output
Step 1: Create first function
Step 3: Call first function
Comments
Post a Comment