【问题标题】:Difference between module scope and function scope模块范围和功能范围的区别
【发布时间】:2016-03-28 15:17:37
【问题描述】:

虽然我将该结构纳入模块范围:

def test():
    return 1


test = test()
print test

效果很好。

但如果我在函数范围内尝试相同:

def test():
    return 1

def go():
    test = test()
    print test

我收到UnboundLocalError:

Traceback (most recent call last):
  File "my.py", line 16, in <module>
    go()
  File "my.py", line 12, in go
    test = test()
UnboundLocalError: local variable 'test' referenced before assignment

我有点困惑。为什么这些行为之间会有这样的差异?

【问题讨论】:

    标签: python python-2.7 scope namespaces


    【解决方案1】:

    在本例中,test 定义在同一个作用域内,因此使用 test 将引用该函数。

    def test():
        return 1
    
    
    test = test()
    print test
    

    在本例中,以test= 开头的行将立即删除对该函数的本地引用,并将其标记为尚未分配,因此当您使用test() 时,它会告诉您该变量不是分配的。

    def test():
        return 1
    
    def go():
        # here
        test = test()
        print test
    

    要获得与第一个示例类似的行为,您可以在我标记为 # here 的位置添加 nonlocalglobal,我很确定您会获得相同的行为。

    【讨论】:

      【解决方案2】:

      在第二个示例中,Python 尝试在分配之前引用 test。 需要根据您的要求将test 声明为nonlocalglobal

      这里是修改后的代码:

      def test():
          return 1
      
      def go():
          global test
          test = test()
          print test
      

      输出

      Win32 上的 Python 2.7.9(默认,2014 年 12 月 10 日,12:24:55)[MSC v.1500 32 位(英特尔)] 输入“copyright”、“credits”或“license()”了解更多信息。

      ================================= 重启============== ===================

      1
      

      【讨论】:

        【解决方案3】:

        问题是,当您将“test”定义为“go”函数范围内的局部变量时,它会在函数命名空间中创建新变量。因此,当您在函数内部调用“test()”时,它会尝试访问其本地副本不是全局函数。下面的代码应该可以工作。

        def test():
            return 1
        
        def go():
            local_function_variable = test()
            print local_function_variable
        
        go()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-03-28
          • 2021-01-21
          • 2019-06-16
          • 1970-01-01
          • 2012-12-11
          • 2015-09-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多