Practice content:
(1) function adorner.
(2) using the Magic Method __call__, a class is implemented as an adorner .
(3) using the Magic method __enter__ and __exit__, a class is implemented so that it can provide context management functions for functions.
1. Function Adorner
1 __author__='Orcsir'2 fromFunctoolsImportWraps, Update_wrapper3 Import Time4 5 6 #implement a function as an adorner7 defTimeit (func):8 @wraps (func)9 def_wrapper (*args, * *Kwargs):Ten Print("Inject Some code before func run.") One Aret = func (*args, * *Kwargs) - - Print("Inject Some code after func run.") the - returnret - - return_wrapper + - + @timeit A defFunc (*args, * *Kwargs): at Print("func start processing.") -Time.sleep (2)#Simulated processing time - Print("func end processing.") - returnNone - - #Test inFunc (.)
2. Use the Magic method __call__ to implement a class as an adorner
1 __author__='Orcsir'2 fromFunctoolsImportWraps, Update_wrapper3 Import Time4 5 #implement a class as an adorner6 classTimeit:7 def __init__(self, wrapped):8Self.__wrapped=Wrapped9 Wraps (wrapped) (self)Ten One def __call__(Self, *args, * *Kwargs): A Print("Inject Some code before func run.") -ret = self.__wrapped(*args, * *Kwargs) - Print("Inject Some code after func run.") the returnret - - - @TimeIt + defFunc (*args, * *Kwargs): - Print("func start processing.") +Time.sleep (2)#Simulated processing time A Print("func end processing.") at returnNone - - #Test -Func ()
3. Using the Magic method __enter__ and __exit__, implement a class that enables it to provide context management functionality for functions
1 __author__='Orcsir'2 fromFunctoolsImportWraps, Update_wrapper3 Import Time4 5 #implement a class that provides context management functionality for a function6 classContextmage4func:7 def __init__(Self, func):8Self.__func=func9 Ten def __enter__(self): One Print("prepares the environment for the Func function's run.") A returnSelf.__func - - def __exit__(self, exc_type, Exc_val, EXC_TB): the Print("when the Func function exits or an exception occurs, do some cleanup work.") - - - defFunc (*args, * *Kwargs): + Print("func start processing.") -Time.sleep (2)#Simulated processing time + Print("func end processing.") A returnNone at - #Test - With Contextmage4func (func): -Func (1, 2) - Print("~~~~~~~~~~~~~~~~~~~~~~") - With Contextmage4func (func) as F: inF (1, 2)
Basic knowledge of Python programming practice _002