DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

关于Python的嵌套域(nested scope)


周五下午因为嵌套函数的问题反复折腾了几个小时,今天终于搞明白了,python2.6手册里对“nested scope”有一段定义,并结合“OReilly - Python in a Nutshell”第4.10.6.2节,总结如下: 1 python支持嵌套函数; 2 内层函数可以访问外层函数中定义的变量,但不能重新赋值(rebind); 3 内层函数的local namespace不包含外层函数定义的变量(见下面的演示程序); 4 避免出现低版本(<=2.1)不支持nested scope问题的方法:在内层函数参数列表中使用默认参数: (copied from "OReilly - Python in a Nutshell" section 4.10.6.2) def make_adder_1(augend): # works with any version def add(addend, _augend=augend ): return addend+_augend return add 演示程序: def outterfunc(): def innerfunc(): cc = bb+'2' print 'inner:',locals() # bb = 3 #这句会造成运行失败 bb = '3' outer = 'out' innerfunc() print 'outter:',locals() bb=31 outterfunc() 输出: inner: {'cc': '32', 'bb': '3'} outter: {'innerfunc': , 'outer': 'out', 'bb': '3'}

从输出可以看到,外层函数里定义的outer变量没有出现在内层函数的local namespace里,但被引用的变量bb却出现了,这一特点值得注意。



Published

Jan 17, 2011

Last Updated

Jan 17, 2011

Category

Tech

Tags

  • nested 1
  • Python 136
  • scope 1

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor