Python:为什么两个全局变量有不同的行为?
问题描述:
我有一段这样的代码。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()
答
如果您分配到的函数体的变量,那么Python把该变量作为本地(除非你把它声明全局)。如果您只是读取函数体内的值而不分配给它,则它会在更高范围内查找变量(例如,父函数或全局函数)。
所以在你的情况,区别在于你分配到commentsMade
,这使得它是本地的,但你不分配给TARGET_LINES
,所以它寻找它的全局定义。