Scope

来源:互联网 发布:宽带连接软件下载 编辑:程序博客网 时间:2024/05/18 01:49
The problem of shadowing
Reading the value of global variables is not a problem in general, but one thing may make it problematic. If a local variable or parameter exists with the same name as the global variable you want to access, you can't do it directly. The global variable is shadowed by the local one.If needed, you can still gain access to the global variable by using the function globals.

>>> def combine(parameter):print parameter + globals()['parameter']...>>> parameter = 'berry'>>> combine('Shrub')Shrubberry
Here from the use of globals(), we can view the namespace as a dictionary  but with the mark of list "[ ]"
Rebinding global variables (making them refer to some new value) is another matter. If you assign a value to a variable inside a function, it automatically becomes local unless you tell Python otherwise.
>>> x = 1>>> def change_global():global xx = x + 1>>> change_global()>>> x2
Nested scopes
Nesting is normally not all that useful, but there is one particular application that stands out: using one function to "create"another. This means that you can (among other things) write functions like the following:
def multiplier(factor):         def multiplyByFactor(number):               return number*factor      return multiplyByFactor
One function is inside another, and the outer function returns the inner one; that is, the function itself is returned—it is not called. What's important is that the returned function still has access to the scope where it was defined; in other words, it carries its environment (and the associated local variables) with it!
Because of Python's nested scopes, this variable from the outer local scope (of multiplier) is accessible in the inner function later on, as follows:
>>>double = multiplier(2)>>>double(5)10>>>multiplier(5)(4)20