我知道LEGB规则。但是,一个函数是否具有对封闭函数中定义的变量的读取访问权限的简单测试看起来并不实际。即:为什么我的函数不能在封闭函数中访问变量?
#!/usr/bin/env python2.4
'''Simple test of Python scoping rules'''
def myfunction():
print 'Hope this works: '+myvariable
def enclosing():
myvariable = 'ooh this worked'
myfunction()
if __name__ == '__main__':
enclosing()
返回:
NameError: global name 'myvariable' is not defined
难道我做错了什么?除了LEGB决议命令还有更多吗?
只是命名函数“enclosing”不会使它如此:) – 2010-06-01 09:27:10
是的。我错误地认为'包含'包含的调用函数,但它实际上是指嵌套函数的父项。 – mikemaccana 2010-06-01 09:44:45
没有必要恢复有效的标签。这不是关于你,而是关于这个问题。 – SilentGhost 2010-06-01 09:46:00