【问题标题】:'global' in python can reference to undefined variable?python中的“全局”可以引用未定义的变量吗?
【发布时间】:2018-02-12 08:33:43
【问题描述】:

在学习 Python 的 LEGB 范围规则时,我想更深入地了解全局在 Python 中的工作原理。似乎即使我引用了一个未定义的变量(这也不是内置的),该代码也不会给我一个错误。请帮我弄清楚到底发生了什么。

def hey():
    x = 1
    def hey2():
        global ew #ew not defined in the module
        x = 2
        print(x)
    hey2()
    print(x)
hey()

OUTPUT: 2
        1

【问题讨论】:

标签: python python-3.x python-2.7 scope global


【解决方案1】:

关键字global用于在本地创建或更新全局变量

def hey():
    x = 1
    def hey2():
        global ew #reference to create or update a global variable named ew
        ew=2 # if you comment this global variable will not be created 
        x = 2
        #print(x)
    hey2()
    #print(x)
print '\t ------Before function call-----'
print globals()
hey()

print '\n'
print '\t -----After function call------ '
print globals()

globals() 将为您提供全局范围包含的所有对象的字典

您可以在第二个字典中看到ew 存在,而在第一个字典中不存在

【讨论】:

    【解决方案2】:

    是的,global statement 可以应用于未绑定的名称(未定义的变量)甚至从未使用过的名称。它不会创建名称,而是通知编译器该名称只能在全局范围内查找,而不是在本地范围内。不同之处在编译后的代码中显示为不同的操作:

    >>> def foo():
    ...   global g
    ...   l = 1
    ...   g = 2
    ...
    >>> dis.dis(foo)
      3           0 LOAD_CONST               1 (1)
                  3 STORE_FAST               0 (l)
    
      4           6 LOAD_CONST               2 (2)
                  9 STORE_GLOBAL             0 (g)
                 12 LOAD_CONST               0 (None)
                 15 RETURN_VALUE
    

    我们看到STORE_FAST 用于局部变量,而STORE_GLOBAL 用于全局变量。 global 语句本身没有任何输出;它只改变了对g 的引用的操作方式。

    【讨论】:

      【解决方案3】:

      两个函数中全局变量的简单示例 定义嘿(): 全局 x x = 1 打印 x hey() # 打印 1 定义嘿2(): 全局 x x += 2 打印 x hey2() #prints 3

      【讨论】:

        猜你喜欢
        • 2018-09-17
        • 1970-01-01
        • 2020-10-05
        • 2018-05-22
        • 1970-01-01
        • 2010-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多