Scope

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 x
x = x + 1
>>> change_global()
>>> x
2
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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值