2016-06-18 102 views
0

我有一段這樣的代碼。Python:爲什麼兩個全局變量有不同的行爲?

有了這個代碼,我得到一個:

local variable 'commentsMade' referenced before assignment 

爲什麼需要在第一功能「全球commentsMade」聲明,但我不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() 

回答

1

如果您分配到的函數體的變量,那麼Python把該變量作爲本地(除非你把它聲明全局)。如果您只是讀取函數體內的值而不分配給它,則它會在更高範圍內查找變量(例如,父函數或全局函數)。

所以在你的情況,區別在於你分配到commentsMade,這使得它是本地的,但你不分配給TARGET_LINES,所以它尋找它的全局定義。

相關問題