i wonder, why have error of unboundlocalerror: local variable 'i' referenced before assignment or nameerror: global name 'i' not defined in following code:
def method1(): = 0 def _method1(): # global -- same error += 1 print 'i=', # = 0 -- same error _method1() method1() how rid of it? i should not visible outside of method1()
one way in py2x pass variable internal method, in py3x has been fixed , can use nonlocal statement there.
the error raised because functions objects , evaluated during definition, , during definition python sees i += 1 (which equivalent i = + 1) thinks i local variable inside function. but, when function called fails find value i (on rhs ) locally , error raised.
def method1(): = 0 def _method1(i): += 1 print 'i=', return #return updated value i=_method1(i) #update print method1() or use function attribute:
def method1(): method1.i = 0 #create function attribute def _method1(): method1.i += 1 print 'i=', method1.i _method1() method1() for py3x:
def method1(): =0 def _method1(): nonlocal += 1 print ('i=', i) _method1() method1()
Comments
Post a Comment