【问题标题】:Python: Why two global variables have different behaviours? [duplicate]Python:为什么两个全局变量有不同的行为? [复制]
【发布时间】:2016-06-18 02:47:14
【问题描述】:

我还有一段这样的代码。

使用此代码,我得到:

local variable 'commentsMade' referenced before assignment

为什么我需要在第一个函数中使用“global cmetsMade”语句,但不需要使用 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 scope global-variables local-variables


    【解决方案1】:

    如果您在函数体中对变量进行赋值,那么 Python 会将变量视为局部变量(除非您将其声明为全局变量)。如果你只是读取函数体中的值,而不给它赋值,那么它会在更高的范围(例如,父函数或全局)中查找变量。

    所以在你的情况下,不同之处在于你分配给commentsMade,这使它成为本地的,但你没有分配给TARGET_LINES,所以它为它寻找一个全局定义。

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 2021-07-18
      • 1970-01-01
      • 2019-02-03
      • 2023-03-16
      • 2018-07-07
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多