Python inner functions -
in python, can write :
def func(): x = 1 print x x+=1 def _func(): print x return _func test = func() test() when run it, output :
1
2
as _func has access "x" variable defined in func. right...
but if :
def func(): x = 1 print x def _func(): x+=1 print x return _func test = func() test() then got error message : unboundlocalerror: local variable 'x' referenced before assignment
in case, seems _func cannot "see" "x" variable
the question is: why print x in first example "see" "x" variable, whereas mathematical operator x+=1 throws exception?
i don't understand why...
check answer : https://stackoverflow.com/a/293097/1741450
variables in scopes other local function's variables can accessed, can't rebound new parameters without further syntax. instead, assignment create new local variable instead of affecting variable in parent scope. example:
Comments
Post a Comment