0
>>> def bar():
        abc = 0
        def run():
            global abc
            abc += 1
            print abc
        return run

>>> ccc = bar()
>>> ccc()

Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    ccc()
  File "<pyshell#50>", line 5, in run
    abc += 1
NameError: global name 'abc' is not defined

as shown in the code, variable 'abc' is defined in function 'bar', a function defined in 'bar' want to access 'abc', I tried to use global declaration before use, but it seem the inner function 'run' only search 'abc' in the outer most namespace. so, how to access 'abc' in function 'run'?

yuyan
  • 19
  • 3

1 Answers1

1

If you are using 3.x, you can use "nonlocal abc" instead of "global abc"

def bar():
    abc = 0
    def run():
        nonlocal abc
        abc += 1
        print (abc)
     return run

in 2.x You can use below style

def bar():
    abc = 0
    def run(abc=abc):
         abc += 1
         print abc
    return run
AlokThakur
  • 3,599
  • 1
  • 19
  • 32
  • thanks for your answer, in 2.x, def run(abc = abc), here abc was pass by value, abc value cannot be change everytime when run is called. and just take value 0 and add 1 but cannot store back to the initial abc – yuyan Jan 23 '16 at 16:13