在函数内部,在内部函数定义之前调用,报错

def str(s):
print 'global str()'


def foo():
    str('dummy')
    def str(s):
        print 'closure str()'
    str('dummy')

def bar():
    str('dummy')
    print 'call'


foo()
bar()

现象: 在foo()函数里面 第一次调用str的时候 提示:

UnboundLocalError: local variable 'str' referenced before assignment

问题:
1. 在运行foo()的时候,第一次调用str, foo本地命名空间没有str的定义,这时候要去外部找str, 为什么会找不到外部定义的str
2. foo内部有str的定义, 解释器第一次读入foo定义的时候, 内部的str要怎么处理
3. 为什么会报这个错误, 类似的bar(), 为什么能够找到外部的str

谢谢~~

阅读 5k
1 个回答

https://docs.python.org/2/reference/executionmodel.html

If a name binding operation occurs anywhere within a code block, all
uses of the name within the block are treated as references to the
current block. This can lead to errors when a name is used within a
block before it is bound. This rule is subtle. Python lacks
declarations and allows name binding operations to occur anywhere
within a code block. The local variables of a code block can be
determined by scanning the entire text of the block for name binding
operations.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题