From 0231aa61bc4a97d031597e3e2187bc8316d4fb01 Mon Sep 17 00:00:00 2001 From: harshal Date: Mon, 7 Jun 2021 21:07:12 +0530 Subject: [PATCH] Add python decorator and examples --- sheets/_python3/decorator | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 sheets/_python3/decorator diff --git a/sheets/_python3/decorator b/sheets/_python3/decorator new file mode 100644 index 0000000..661a6b1 --- /dev/null +++ b/sheets/_python3/decorator @@ -0,0 +1,41 @@ +# A decorator is a design pattern in Python that allows a user +# to add new functionality to an existing object without modifying +# its structure. Decorators are usually called before the definition +# of a function you want to decorate. +# In simple words: they are functions which modify the functionality +# of other functions. + +from datetime import datetime + +def my_decorator(func): + def wrapper(): + print('start', datetime.now()) + func() + print('end', datetime.now()) + return wrapper + +@my_decorator +def my_method(): + for i in range(1, 100000): + pass + +my_method() +# start 2021-06-07 15:29:51.330086 +# end 2021-06-07 15:29:51.333832 + +# Decorator with function parameters. +def my_decorator(func): + def wrapper(start, end): + print('start', datetime.now()) + func(start, end) + print('end', datetime.now()) + return wrapper + +@my_decorator +def my_method(start, end): + for i in range(start, end): + pass + +my_method() +# start 2021-06-07 15:29:51.330086 +# end 2021-06-07 15:29:51.333832 \ No newline at end of file