2011-12-20 4 views
1

可能性の重複:次の関数で
Read/Write Python Closures内部関数を囲む関数の変数を見ますか?

、内部関数は、引数を変更するだけでなく、コピーを変更しません。

def func(): 
    i = 3 
    def inc(i): 
    i = i + 3 
    print i 
    inc(i) 
    inc(i) 
    print i 

func() 

繰り返しコードを避けて、それをPythonの関数の中に入れることはできますか?私も次のことを試してみましたが、何について​​

def func(): 
    i = 3 
    def inc(): 
    i = i + 3 
    print i 
    inc() 
    inc() 
    print i 

func() 
+0

私のお気に入りのインタビューの質問の1つです。私はあなたがPythonで変数の可視性について読むことをお勧めします。 – lig

+0

[Read/Write Python Closures]の重複可能性があります(http://stackoverflow.com/q/2009402/395760) – delnan

+0

も参照してください:http://stackoverflow.com/q/8447947/331473 –

答えて

3

変数が外側スコープにあるために機能しませんが、グローバル変数ではありません。したがって、変数を引数として渡す必要があります。

これはPEP 3104の問題です。

2

エラーがスローされます。globalを使ってPython 2.xで

def func(): 
    i = 3 
    def inc(): 
    nonlocal i 
    i = i+3 
    print(i) 
    inc() 
    inc() 
    print(i) 

func() 

:あなたはこれを行うだろうとのpython 3では

def func(): 
    i = 3 
    def inc(i): 
     return i + 3 
    print i 
    i = inc(i) 
    i = inc(i) 
    print i 

func() 
0

Python 3ではnonlocalを使用できます。

>>> def func(): 
    i = 3 
    def inc(): 
     nonlocal i 
     i += 3 
    print(i) 
    inc() 
    inc() 
    print(i) 

>>> func() 
3 
9 
>>> 
関連する問題