首页 文章

在Python中使用“global”关键字

提问于
浏览
249

我从阅读文档中了解到,Python有一个单独的函数命名空间,如果我想在该函数中使用全局变量,我需要使用 global .

我正在使用Python 2.7,我尝试了这个小测试

>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
...     return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'

即使没有 global ,似乎事情也很好 . 我能够毫无问题地访问全局变量 .

我错过了什么吗?此外,以下是来自Python文档:

不能将全局语句中列出的名称定义为形式参数,也不能将其定义为for循环控制目标,类定义,函数定义或import语句 .

虽然形式参数和类定义对我有意义,但我无法理解for循环控制目标和函数定义的限制 .

10 回答

  • 328

    虽然您可以在不使用 global 关键字的情况下访问全局变量,但如果要修改它们,则必须使用 global 关键字 . 例如:

    foo = 1
    def test():
        foo = 2 # new local foo
    
    def blub():
        global foo
        foo = 3 # changes the value of the global foo
    

    在您的情况下,您只是访问列表 sub .

  • 12

    这是在范围内访问名称和binding之间的区别 .

    如果您只是查找变量来读取其值,则可以访问全局和本地范围 .

    但是,如果您为本地范围内的变量's name isn' t分配,则将该名称绑定到此范围中(如果该名称也作为全局存在,则会隐藏该名称) .

    如果您希望能够分配全局名称,则需要告诉解析器使用全局名称而不是绑定新的本地名称 - 这就是'global'关键字的作用 .

    绑定块中的任何位置都会导致该块中的所有名称都被绑定,这可能会导致一些相当奇怪的后果(例如,UnboundLocalError突然出现在以前工作的代码中) .

    >>> a = 1
    >>> def p():
        print(a) # accessing global scope, no binding going on
    >>> def q():
        a = 3 # binding a name in local scope - hiding global
        print(a)
    >>> def r():
        print(a) # fail - a is bound to local scope, but not assigned yet
        a = 4
    >>> p()
    1
    >>> q()
    3
    >>> r()
    Traceback (most recent call last):
      File "<pyshell#35>", line 1, in <module>
        r()
      File "<pyshell#32>", line 2, in r
        print(a) # fail - a is bound to local scope, but not assigned yet
    UnboundLocalError: local variable 'a' referenced before assignment
    >>>
    
  • 6

    Global使变量“全局”

    def out():
        global x
        x = 1
        print(x)
        return
    
    
    out()
    
    print (x)
    

    这使得'x'就像是函数外的正常变量 . 如果你取出全局,那么它会产生错误,因为它无法在函数内打印变量 .

    def out():
         # Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
        x = 1
        print(x)
        return
    
    
    out()
    
    print (x)
    
  • 66

    其他答案回答了你的问题 . 关于Python中名称的另一个重要事项是,它们在每个范围的基础上是本地的或全局的 .

    考虑一下,例如:

    value = 42
    
    def doit():
        print value
        value = 0
    
    doit()
    print value
    

    您可能猜测 value = 0 语句将分配给局部变量,而不会影响在 doit() 函数外声明的同一变量的值 . 您可能会更惊讶地发现上面的代码无法运行 . 函数内部的语句 print value 产生 UnboundLocalError.

    原因是Python注意到,在函数的其他地方,您指定了名称 value ,并且 value 也没有声明 global . 这使它成为一个局部变量 . 但是当您尝试打印它时,尚未定义本地名称 . 在这种情况下,Python不会像其他语言那样回归到将名称作为全局变量进行查找 . 实际上,如果在函数中的任何位置定义了同名的局部变量,则无法访问全局变量 .

  • 2

    这意味着您不应该执行以下操作:

    x = 1
    
    def myfunc():
      global x
    
      # formal parameter
      def localfunction(x):
        return x+1
    
      # import statement
      import os.path as x
    
      # for loop control target
      for x in range(10):
        print x
    
      # class definition
      class x(object):
        def __init__(self):
          pass
    
      #function definition
      def x():
        print "I'm bad"
    
  • 47

    关键字 global 仅对在本地上下文中更改或创建全局变量很有用,尽管创建全局变量很少被认为是一个很好的解决方案 .

    def bob():
        me = "locally defined"    # Defined only in local context
        print me
    
    bob()
    print me     # Asking for a global variable
    

    以上将给你:

    locally defined
    Traceback (most recent call last):
      File "file.py", line 9, in <module>
        print me
    NameError: name 'me' is not defined
    

    而如果使用 global 语句,变量将变为可用"outside"函数的范围,有效地成为全局变量 .

    def bob():
        global me
        me = "locally defined"   # Defined locally but declared as global
        print me
    
    bob()
    print me     # Asking for a global variable
    

    所以上面的代码会给你:

    locally defined
    locally defined
    

    此外,由于python的性质,您还可以使用 global 在本地上下文中声明函数,类或其他对象 . 虽然我会反对它,因为如果出现问题或需要调试它会导致噩梦 .

  • 0

    我将举一个简单的例子:想想这段代码:

    myVar = 0 
    print (myVar )      # 01 line: returns 0
    
    def func():
        myVar  = "def"
        print (myVar )
    
    func()              # 02 line: returns def
    print (myVar )      # 03 line: returns 0
    

    正如您所看到的,最后一行代码将返回0,因为在函数内部 myVar 变量未被重新分配,它刚刚被修改,它将更改 only when the function called without affecting the main myVar variable , because it defined inside the our function (means it is local variable) ,但使用全局关键字如下:

    myVar  = 0 
    print (myVar )       # 01 Line : returns 0
    
    def func():
        global myVar 
        myVar  = "def"
        print (myVar )
    
    func()               # 02 Line : returns def
    print (myVar )       # 03 Line : returns def
    

    我们实际上命令python,def中的这个变量不是本地的,使用名为 myVar 的全局变量来改变它 .

  • 0

    访问名称和分配名称是不同的 . 在您的情况下,您只是访问一个名称 .

    如果分配给函数中的变量,则假定该变量是本地变量,除非您将其声明为全局变量 . 如果没有,则假定它是全球性的 .

    >>> x = 1         # global 
    >>> def foo():
            print x       # accessing it, it is global
    
    >>> foo()
    1
    >>> def foo():   
            x = 2        # local x
            print x 
    
    >>> x            # global x
    1
    >>> foo()        # prints local x
    2
    
  • 192
    • 您可以访问没有关键字 global 的全局关键字

    • 为了能够修改它们,您需要明确声明关键字是全局的 . 否则,关键字将在本地范围内声明 .

    例:

    words = [...] 
    
    def contains (word): 
        global words             # <- not really needed
        return (word in words) 
    
    def add (word): 
        global words             # must specify that we're working with a global keyword
        if word not in words: 
            words += [word]
    
  • 0

    在函数外部声明的任何变量都假定为全局变量,只有在从函数内部(构造函数除外)声明它们时才必须指定它们变量是全局的 .

相关问题