2015/9/19 Python Basics (14): Variable scope and generator

Source: Internet
Author: User
Tags variable scope

Variable scope
The scope of an identifier is the scope of the application defined for its declaration, or that is what we call variable visibility. That is, we can access a set identifier in that part of the program.
Global variables and local variables
Variables defined within a function have local scope, and the highest-level variables in a module have global scope.
A feature of global variables is that unless they are removed, they will survive until the end of the script, and for all functions, their values are accessible, while local variables, like the stacks they hold, are temporarily present, relying only on the function that defines them to be active at this stage. When a function call appears, its local variables enter the scope in which they are declared. At that moment, a new local variable named that object was created, and once the function is complete, the framework is freed and the variable leaves the scope.

Global statement
If the name of the global variable is declared in a function body, the name of the global variable can be overwritten by a local variable. In order to explicitly refer to a named global variable, you must use the global statement with the following syntax:

Global var1[, Var2...varn]

Closed Package
In an intrinsic function, a reference to a variable that is in an outer scope (but not at the global scope) is considered a closure (closure). A variable defined within an external function but caused by or used by an intrinsic function is called a free variable. Closure is an important concept in functional programming, and scheme and Haskell are two of the functional programming.
Closures combine the internal function's own code and scope with the function of an external function.
Here's a simple example:

def addup (number): def addup_in (number_in): Print number_in return number+number_in  return  addup_in# This value is passed to number # This value is passed to number_in. # This value is passed to number_in 510.

Scope and Lambda
Python's lambda anonymous functions follow the same scoping rules as standard functions. A lambda expression defines a new scope, like a function definition, so that the scope is inaccessible to other parts of the program, except for the local lambda function.

Generator
The generator originates from the iterator, and the role of the iterator is to invoke next () to get the next element, if we want the iteration to generate the next value in some way and return to the next () call. This is one of the motivations for developing a birth generator.
The generator is a function with a yield statement. A function or subroutine is returned only once, but a generator can pause execution and return an intermediate result-the effect of the yield statement. When the next () method of the generator is called, it will continue exactly where it left off.


Simple Generator Features
Similar to iterators, the generator works in a different way: when a real return is reached or the function ends without more values returned (when you call Next ()), a Stopiteration exception is thrown.
Here is an example of a simple generator:

>>>defSimplegen ():yield1yield '2 --punch!'>>> Myg =Simplegen ()>>>Myg.next ()1>>>Myg.next ()'2 --punch!'>>>Myg.next () Traceback (most recent): File"<pyshell#29>", Line 1,inch<module>Myg.next () stopiteration because the For Loop has next () calls and handles to the stopiteration, you can iterate through a generator with a for loop iteration. >>> forEachiteminchSimplegen ():PrintEachitem---punch!

Enhanced generator Features
Instead of using next () to get the next generated value, the user can send the value back to the generator [Send ()], throw an exception in the generator, and ask to exit [Close ()]
Since the bidirectional action involves code called send () to send a value to the generator (and the value returned by the generator is sent back), the yield statement must now be an expression, because you may be receiving an incoming object when the answer generator continues execution. Here is a simple example of a write feature, which is a simple closure example:

>>>defCounter (start_at=0): Count=Start_at whileTrue:val= (yieldcount)ifVal is  notNone:count=ValElse: 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): File"<pyshell#48>", Line 1,inch<module>count.next () stopiteration

2015/9/19 Python Basics (14): Variable scope and generator

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.