Python | what is a closure, Generator Generator how to grasp

2022-06-09 0 By

Closure is a short term for Lexical Closure, and is a function that references free variables. For example, when Lexical Closure is used for Lexical Closure, it is used for Lexical Closure. For example, when Lexical Closure is used for Lexical Closure, it is used for Lexical Closure.The referenced free variable will exist with the function, even if it has left the environment in which it was created.Therefore, there is another way to say that closures are entities composed of functions and their associated reference environments.Extension: Closure defines an inner function within an outer function that uses temporary variables from the outer function and returns a reference to the inner function.So this is a closure.(equivalent to aliasing an inner function).Implementation rules :① Define internal function ② external function must have a return value, and the return value must be the definition of internal function object closure structure, example ch08-demo12-closureTwo ways to create generators/Use the Yield keyword Generator is a new data type introduced by the ES6 standard, which features the surrender of execution of functions, i.e. the suspension of execution.A generator looks like a function, but can return multiple times. The difference is that the function name is preceded by an asterisk *, which, in conjunction with the yield command, provides pause for execution.Extension: The Generator was mentioned earlier when we looked at the derivation.Recall: using () does not represent a tuple derivation, but rather implements a generator where the parser generates data in real time and the data does not reside in memory.Therefore, its execution efficiency is very high!Get a lot of data, the data generation rule uses the derivation to quickly create a generator example ch07-demo14-generator. py Extension: generator yield keyword ● Yield is a keyword similar to retum, except that the function returns a generator ● When you call this functionThe code inside the function does not execute immediately, the function simply returns – a generator object ● The code in the function executes only when you iterate with for. Use yield to create a generator example ch07-demo14-generator.py