3

我想知道,为什么我在以下代码中出现UnboundLocalError: local variable 'i' referenced before assignment或错误:NameError: global name 'i' is not defined

def method1():
  i = 0
  def _method1():
    # global i -- the same error
    i += 1
    print 'i=', i

  # i = 0 -- the same error
  _method1()

method1()

我该如何摆脱它?i不应该在外面可见method1()

4

1 回答 1

2

One way to do this in py2x is to pass the variable itself to the internal method, in py3x this has been fixed and you can use nonlocal statement there.

The error is raised because functions are objects too and are evaluated during their definition, and during definition as soon as python sees i += 1 (which is equivalent to i = i + 1) it thinks that i is a local variable inside that function. But, when the function is actually called it fails to find any value for the i (on the RHS ) locally and thus the error is raised.

def method1():
  i = 0
  def _method1(i):
    i += 1
    print 'i=', i
    return i     #return the updated value

  i=_method1(i)  #update i
  print i

method1()

or use a function attribute:

def method1():
  method1.i = 0       #create a function attribute
  def _method1():
    method1.i += 1
    print 'i=', method1.i

  _method1()

method1()

For py3x:

def method1():
  i =0 
  def _method1():
    nonlocal i  
    i += 1
    print ('i=', i)
  _method1()

method1()
于 2013-05-06T09:27:22.977 回答