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

py2x でこれを行う 1 つの方法は、変数自体を内部メソッドに渡すことです。py3x ではこれが修正されており、nonlocalそこでステートメントを使用できます。

関数もオブジェクトであり、定義中に評価されるため、エラーが発生します。また、定義中に python がi += 1(と同等であるi = i + 1)を認識するとすぐに、それはiその関数内のローカル変数であると見なされます。しかし、関数が実際に呼び出されると、iローカルで ( RHS の) の値を見つけることができないため、エラーが発生します。

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()

または関数属性を使用します。

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

  _method1()

method1()

py3x の場合:

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

method1()
于 2013-05-06T09:27:22.977 に答える