How do I change nesting function's variable in the nested function

给你一囗甜甜゛ 提交于 2019-11-29 01:26:21

In Python 3.x, you can use the nonlocal declaration (in nested) to tell Python you mean to assign to the count variable in nesting.

In Python 2.x, you simply can't assign to count in nesting from nested. However, you can work around it by not assigning to the variable itself, but using a mutable container:

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

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

Although for non-trivial cases, the usual Python approach is to wrap the data and functionality in a class, rather than using closures.

A little bit late, you can attach an attribute to "nesting" function like so:

def nesting():

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

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

c = nesting()
print(c.count)

The most elegant approach for me: Works 100% on both python versions.

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!