Python:为什么两个全局变量具有不同的行为



我有一个类似的代码。

使用此代码,我得到了:

local variable 'commentsMade' referenced before assignment

为什么我需要第一个功能中的"全局评论"语句,而我不需要target_lines?(使用Python2.7)

TARGET_LINE1 = r'someString'
TARGET_LINE2 = r'someString2'
TARGET_LINES = [TARGET_LINE1, TARGET_LINE2]
commentsMade = 2
def replaceLine(pattern, replacement, line, adding):
    #global commentsMade  # =========> Doesn't work. Uncommenting this does!!!!
    match = re.search(pattern, line)
    if match:
        line = re.sub(pattern, replacement, line)
        print 'Value before = %d ' % commentsMade
        commentsMade += adding
        print 'Value after = %d ' % commentsMade
    return line
def commentLine(pattern, line):
    lineToComment = r'(s*)(' + pattern + r')(s*)$'
    return replaceLine(lineToComment, r'1<!--2-->3', line, +1)
def commentPomFile():
    with open('pom.xml', 'r+') as pomFile:
        lines = pomFile.readlines()
        pomFile.seek(0)
        pomFile.truncate()
        for line in lines:
            if commentsMade < 2:
                for targetLine in TARGET_LINES: # ===> Why this works???
                    line = commentLine(targetLine, line)
            pomFile.write(line)
if __name__ == "__main__":
    commentPomFile()

如果您对函数正文中的变量进行分配,则Python将该变量视为局部(除非您将其声明为全局)。如果您只读取函数正文内的值,而无需分配该值,则它在较高范围(例如,父函数或全局)中查找变量。

因此,在您的情况下,区别在于您将其分配给commentsMade,这使其成为本地,但您不分配给TARGET_LINES,因此它为其寻找全局定义。

相关内容

  • 没有找到相关文章

最新更新