Python: 为什么两个全局变量有不同的行为?
Python: Why two global variables have different behaviours?
我下面有一段这样的代码。
使用这段代码我得到:
local variable 'commentsMade' referenced before assignment
为什么我需要在第一个函数中使用 'global 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'<!---->', 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
,所以它会为它寻找一个全局定义.
我下面有一段这样的代码。
使用这段代码我得到:
local variable 'commentsMade' referenced before assignment
为什么我需要在第一个函数中使用 'global 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'<!---->', 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
,所以它会为它寻找一个全局定义.