2017-08-23 7 views
0

Pythonの閉鎖機能があります:delがパラメータに対してUnboundLocalErrorを生成するのはなぜですか?

def test(a): 
    def delete(): 
     print "first", a 
    delete() 
    print "second", a 

test(1) 

、出力は次のとおりです。

first 1 
second 1 

その後、我々は別の関数試してみてください。

def test(a): 
    def delete(): 
     print "first", a 
     del a 
    delete() 
    print "second", a 

test(1) 

を我々は出力を得る:

UnboundLocalError 
Traceback (most recent call last) 
<ipython-input-28-c61f724ccdbf> in <module>() 
     6  print "second", a 
     7 
----> 8 test(1) 

<ipython-input-28-c61f724ccdbf> in test(a) 
     3   print "first", a 
     4   del a 
----> 5  delete() 
     6  print "second", a 
     7 

<ipython-input-28-c61f724ccdbf> in delete() 
     1 def test(a): 
     2  def delete(): 
----> 3   print "first", a 
     4   del a 
     5  delete() 

UnboundLocalError: local variable 'a' referenced before assignment 

は、の前にローカル変数になるのはなぜですか?

エラーが名前atest()の範囲にはなくdelete()の範囲にローカルなラインで

print "first", a 

なく

del a 
+0

「del a」は、この点では「a = ...」と同じ効果があると思います。 –

+1

変数の変更は、変数がスコープ内にあることを意味します。外側のスコープ「a」にアクセスするには、 'global'キーワードを使用できます。 – tzaman

+0

@tzaman、エラーはライン印刷で「最初」ですが、aではなくdel aであることに注意してください。それは私の質問です。 – Tyler

答えて

1

であることに注意してください。

あなたはdel aにしようとしているので、Pythonのは、それがされていない、ローカルであるaを前提としています。

最後に、でエラーが発生します.aはローカルであると見なされるため、この時点で印刷する前に定義されていないためです。

+0

それは理にかなっています。 – Tyler

関連する問題