2016-06-18 2 views
0

私はこのようなコードをもう少し持っています。このコードでは Python:2つのグローバル変数の動作が異なるのはなぜですか?

は私が取得:

local variable 'commentsMade' referenced before assignment 

なぜ私は最初の関数で「グローバルcommentsMade」ステートメントを必要とするが、私はTARGET_LINESを必要としないのですか?あなたは関数の本体内の変数への割り当てを行った場合(あなたはそれがグローバル宣言しない限り)

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

を(Python2.7を使用して)、そしてPythonはローカル変数として扱われます。関数の本体内の値を割り当てずに読み込んだ場合は、上位の変数(親関数やグローバル変数など)の変数を探します。

あなたの場合は、commentsMadeに割り当てるとローカルになりますが、TARGET_LINESには割り当てられないため、グローバル定義が検索されます。

関連する問題