【问题标题】:Function not changing global variable函数不改变全局变量
【发布时间】:2012-09-30 23:21:17
【问题描述】:

我的代码如下:

done = False

def function():
    for loop:
        code
        if not comply:
            done = True  #let's say that the code enters this if-statement

while done == False:
    function()

由于某种原因,当我的代码进入 if 语句时,它在使用 function() 完成后并没有退出 while 循环。

但是,如果我这样编码:

done = False

while done == False:
    for loop:
    code
    if not comply:
        done = True  #let's say that the code enters this if-statement

...它退出while循环。这是怎么回事?

我确保我的代码进入了 if 语句。我还没有运行调试器,因为我的代码有很多循环(相当大的二维数组),我放弃了调试,因为它太乏味了。为什么“完成”在函数中没有被更改?

【问题讨论】:

标签: python global-variables


【解决方案1】:

您的问题是函数创建了自己的命名空间,这意味着函数中的 done 与第二个示例中的 done 不同。使用global done 来使用第一个done,而不是创建一个新的。

def function():
    global done
    for loop:
        code
        if not comply:
            done = True

global的使用说明见here

【讨论】:

    【解决方案2】:
    done=False
    def function():
        global done
        for loop:
            code
            if not comply:
                done = True
    

    你需要使用 global 关键字让解释器知道你引用了全局变量done,否则它会创建另一个只能在函数中读取的变量。

    【讨论】:

      【解决方案3】:

      使用global,只有这样你才能修改全局变量,否则函数内的done = True之类的语句将声明一个名为done的新局部变量:

      done = False
      def function():
          global done
          for loop:
              code
              if not comply:
                  done = True
      

      阅读更多关于the global statement的信息。

      【讨论】:

        【解决方案4】:

        使用class 而不是global

        另一种处理(不使用)全局变量的方法是将您希望成为全局变量的函数和变量包装在一个中。

        虽然这对于这个特定案例来说有点繁重 - 类为项目添加了许多功能和灵活性。 (个人)强烈推荐。

        例如:

        class Processor():
            """Class container for processing stuff."""
        
            _done = False
        
            def function(self):
                """A function which processes stuff."""
                # Some code here ...
                self._done = True
        
        # See the flag changing.
        proc = Processor()
        print('Processing complete:', proc._done)
        proc.function()
        print('Processing complete:', proc._done)
        

        输出:

        Processing complete: False
        Processing complete: True
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-31
          • 1970-01-01
          • 2021-12-12
          • 1970-01-01
          相关资源
          最近更新 更多