Decorative Device
1. Quick Check Notes
# --function adorner: the declaration of the runtime of the function behind it consists of the @ symbol and the immediately following "meta-function" (Metafunction ) @staticmethod defprint(x) # is equivalent to : defprint(x) = Staticmethod (Smeth)
Definition: A way to dynamically add functionality during code runs, called an "adorner" (Decorator)
Classic example:
#-*-coding:utf-8-*-Import TimedefTimer (func):#The memory address of the decorated function Ceshi is passed to Func. defDeco (*args,**Kwargs): Start_time=time.time () func (*args,**Kwargs) Stop_time=time.time ()Print('test function Run time', (stop_time-start_time)) returnDeco#returns the memory address of Deco@timerdefCeshi (a): Time.sleep (3) Print('Test%s'%a) Ceshi ('Decorative Device')
2. Principle: ① cannot modify the source code of the decorated function; ② cannot modify the calling method of the decorated function
3. Implement the decorator's skill reserve
The ① function itself is a variable
② higher order functions, one function name as an argument to another function
③ nested functions
Reference: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014318435599930270c0381a3b44db991cd6d858064ac0000
Generator
1. Quick Check Notes
#--Generator function: Yield VS return defGensquare (N): forIinchRange (N):yieldi** 2#status hangs can revert to the state at this point forIinchGensquare (5):#How to use Print(I, end =' ')#[0, 1, 4, 9, +]x = Gensquare (2)#x is a Build objectNext (x)#equivalent to x.__next__ () returns 0Next (x)#equivalent to x.__next__ () returns 1Next (x)#equivalent to x.__next__ () throws an exception stopiteration #--Generator expression: Parentheses for list parsingG = (x * * 2 forXinchRange (3))#use parentheses to create the generator of the desired result generator objectNext (g), Next (g), Next (g)#consistent with the return value of the generator function described above #(1) Generator (generator function/builder expression) is a single Iteration objectG = (x * * 2 forXinchRange (4)) I1= ITER (G)#here actually iter (g) = gNext (I1)#Output 0Next (G)#Output 1Next (I1)#Output 4 #(2) The generator does not retain the result after the iterationGen = (i forIinchRange (4)) inchGen#returns TrueinchGen#returns TrueinchGen#return False, in fact, when detecting 2, 1 is not in the generator, that is, 1 has been iterated, the same 2, 3 is not
2. Generator expressions
Limitations: only suitable for simple algorithms
Example:
for in range (1,10))print(next Test)print(test). __next__())
3. Generator function yield
Example of the Fibonacci function printing:
def fib (max): =0 whilen<Max: yield b = b,a+ b N +=1 return= fib (Test)print. __next__())print(next Test ) for in test: Print(i)
Python3 for quick reference-Python basics, function programming decorators, generators