19

入れ子関数で定義された変数を入れ子関数で変更したいのですが、

def nesting():
    count = 0
    def nested():
        count += 1

    for i in range(10):
        nested()
    print count

入れ子関数が呼び出されたときに、10を出力したいのですが、UnboundLocalErrorが発生します。キーワードglobalはこれを解決するかもしれません。ただし、変数countは入れ子関数のスコープでのみ使用されるため、グローバルとして宣言しないことを期待しています。これを行うための良い方法は何ですか?

4

3 に答える 3

24

Python 3.xでは、nonlocal(の)宣言を使用して、の変数にnested割り当てることをPythonに指示できます。countnesting

Python 2.xでは、からcountinに割り当てることはできません。ただし、変数自体に割り当てるのではなく、可変コンテナを使用することで回避できます。nestingnested

def nesting():
    count = [0]
    def nested():
        count[0] += 1

    for i in range(10):
        nested()
    print count[0]

自明ではない場合でも、通常のPythonのアプローチは、クロージャを使用するのではなく、データと機能をクラスでラップすることです。

于 2011-06-01T09:09:11.053 に答える
5

少し遅れて、次のように「入れ子」関数に属性を付加できます。

def nesting():

    def nested():
        nested.count += 1
    nested.count = 0

    for i in range(10):
        nested()
    return nested

c = nesting()
print(c.count)
于 2014-10-04T08:56:20.923 に答える
0

私にとって最もエレガントなアプローチ:両方のPythonバージョンで100%動作します。

def ex8():
    ex8.var = 'foo'
    def inner():
        ex8.var = 'bar'
        print 'inside inner, ex8.var is ', ex8.var
    inner()
    print 'inside outer function, ex8.var is ', ex8.var
ex8()

inside inner, ex8.var is  bar
inside outer function, ex8.var is  bar

詳細: http: //www.saltycrane.com/blog/2008/01/python-variable-scope-notes/

于 2016-09-16T19:50:05.510 に答える