Python BASICS (14): variable scope and generator, 2015 python

Source: Internet
Author: User

Python BASICS (14): variable scope and generator, 2015 python

Variable Scope
The identifier's scope is defined as its declared applicability, or the variable visibility we call it. That is, we can access a specific identifier in the part of the program.
Global variables and local variables
Variables defined in a function have local scopes, and the most advanced variables in a module have global scopes.
A feature of global variables is that they will survive until the script is running, and their values can be accessed for all functions. However, for local variables, just like the stacks they store, they exist for the moment and only rely on defining whether their functions are active at this stage. When a function call occurs, its local variables enter the scope of declaring them. At that moment, a new local variable named that object is created. Once the function is complete and the framework is released, the variable will leave the scope.

Global Statement
If you declare the name of a global variable in a function, the name of the global variable can be overwritten by a local variable. To explicitly reference a named global variable, the global statement must be used. The syntax is as follows:

global var1[, var2...varN]

 

Closure
In an internal function, when variables in the external scope (but not in the global scope) are referenced, the internal function is considered as a closure ). variables defined in external functions but caused or used by internal functions are called free variables. Closure is an important concept in functional programming. Scheme and Haskell are two types of functional programming.
Closures combine the code, scope, and external functions of internal functions.
The following is a simple example:

>>> Def addup (number): def addup_in (number_in): print number_in return number + number_in return addup_in >>> add = addup (5) # This value is passed to number >>> add (1) # This value is passed to number_in16 >>> add (5) # This value is passed to number_in510

 

Scope and lambda
Lambda anonymous functions in Python follow the same scope rules as standard functions. A lambda expression defines a new scope, just like a function definition. Therefore, apart from a local lambda function, this scope cannot be accessed for other parts of the program.

Generator
The generator is derived from the iterator. The iterator is used to obtain next () of the next element. If we want to generate the next value in some way in the iteration, and return the next () call. This is one of the motivations for developing the generator.
The generator is a function with yield statements. A function or subroutine returns only once, but a generator can pause execution and return an intermediate result-that is, the role of the yield statement. When the next () method of the generator is called, it will accurately continue from the place where it leaves.


Simple generator features
Similar to the iterator, the Generator operates in another way: when a real return is reached or the function ends, no more values are returned (when next () is called ()), A StopIteration exception will be thrown.
The following is a simple generator example:

>>> Def simpleGen (): yield 1 yield '2 --> punch! '>>> MyG = simpleGen () >>> myG. next () 1 >>> myG. next ()' 2 --> punch! '>>> MyG. next () Traceback (most recent call last): File "<pyshell #29>", line 1, in <module> myG. next () StopIteration because the for loop has a next () call and processing of StopIteration, you can use the for loop iteration to pass through a generator. >>> For eachItem in simpleGen (): print eachItem12 --> punch!

 

Enhanced generator features
In addition to using next () to obtain the next generated value, you can send the value back to the generator [send ()], throw an exception in the generator, and request to exit [close ()].
Because two-way actions involve code called send () to send values to the generator (and the values returned by the generator are sent back), the yield statement must be an expression, because when the answer generator continues executing, you may be receiving an incoming object. The following is a simple example of the write feature. This is a simple closure example:

>>> def counter(start_at=0):  count = start_at  while True:    val = (yield count)    if val is not None:      count = val    else:      count += 1>>> count = counter(5)>>> count.next()5>>> count.next()6>>> count.send(9)9>>> count.next()10>>> count.close()>>> count.next()Traceback (most recent call last):File "<pyshell#48>", line 1, in <module>count.next()StopIteration

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.