About the global keyword in python

# coding: utf-8

def func():
    print 'x is', x
    #x = 2   #if I add this line, there will be an error, why?
    print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x 
  • I am not adding a function global xto func, but it can still find xequals 50, why?
  • When I add a line x=2to the func function, there will be an error ( UnboundLocalError: local variable 'x' referenced before assignment), why?
+3
source share
3 answers

The trick is that local names are detected statically :

  • Until a name xis assigned in the function, references to xresolve the global scope
  • x , Python , x . , , x.

: , .

+5

global .

, , , . x , , .

+4

Python . .

global, . . :

x = 'global'
def f():
    x = 'local in f'
    def g():
        global x 
        x = 'assigned in g'
    g()
    print x

f() local in f, x - 'assigned in g'.


Python 3 nonlocal, .

x = 'global'
def f():
    x = 'local in f'
    def g():
        nonlocal x 
        x = 'assigned in g'
    return g
    print(x)

f() ', g (which is the value of x in local scope of f() ), while value of x` .

, Python () , x :

x = 'global'
def f():
    x = 'local in f'
    def g():
        nonlocal x 
        x = 'assigned in g'
    return g
g = f()
g()
+3
source

All Articles