需要帮助了解Python关闭

可能重复:
Python中的UnboundLocalError

我有这样的代码:

import re

def doReplace(toReplace):
    i = 1
    def chapterReplacer(_):
        result = 'Chapter %i' % i
        i += 1
        return result

    return re.sub('Chapter [a-zA-Z]+', chapterReplacer, test)

test = 'Chapter one Chapter Two Chapter three'
print doReplace(test)

当我运行它时,出现以下错误:

Traceback (most recent call last):
  File "C:/Python26/replace.py", line 13, in <module>
    print doReplace(test)
  File "C:/Python26/replace.py", line 10, in doReplace
    return re.sub('Chapter [a-zA-Z]+', chapterReplacer, test)
  File "C:Python26libre.py", line 151, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "C:/Python26/replace.py", line 6, in chapterReplacer
    result = 'Chapter %i' % i
UnboundLocalError: local variable 'i' referenced before assignment

我的印象是章节记者会捕获局部变量i,但这似乎并没有发生?


你可以让i的功能属性

def doReplace(toReplace):
    chapterReplacer.i = 1
    def chapterReplacer(_):
        result = 'Chapter %i' % chapterReplacer.i
        chapterReplacer.i += 1
        return result

    return re.sub('Chapter [a-zA-Z]+', chapterReplacer, test)

编辑:由于python 3,你可以使用nonlocal la @MartijnPieters的解决方案。


不,并且在Python 2中你根本不能使用可变的技巧:

def doReplace(toReplace):
    i = [1]
    def chapterReplacer(_):
        result = 'Chapter %i' % i[0]
        i[0] += 1
        return result

    return re.sub('Chapter [a-zA-Z]+', chapterReplacer, test)

通常情况下,python只会在周围的范围内查找一个变量,如果它没有被分配到本地; 只要字节编译器看到直接赋值( i = something )并且没有global i语句来说服它,否则变量被认为是本地的。

但是在上面的代码中,我们从来没有在chapterReplacer函数中分配给i 。 是的,我们确实改变了i[0]但存储在i本身中的值不会改变。

在python 3中,只需使用nonlocal语句让python查看变量的闭包:

def doReplace(toReplace):
    i = 1
    def chapterReplacer(_):
        nonlocal i
        result = 'Chapter %i' % i
        i += 1
        return result

    return re.sub('Chapter [a-zA-Z]+', chapterReplacer, test)

在Python中,如果您在函数内部赋值变量(即使使用复合赋值运算符(例如+= )),该变量将被视为本地变量,除非global或非nonlocal语句另有指定。

链接地址: http://www.djcxy.com/p/51253.html

上一篇: Need help understanding Python closures

下一篇: Python closure function losing outer variable access