在python中修改内部函数的函数变量 [英] Modify the function variables from inner function in python

查看:409
本文介绍了在python中修改内部函数的函数变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以打印外部函数变量 a

It's ok to get and print the outer function variable a

def outer():
    a = 1
    def inner():
        print a

也可以获得外部函数数组 a 并附加一些内容

It's also ok to get the outer function array a and append something

def outer():
    a = []
    def inner():
        a.append(1)
        print a

然而,当我尝试增加整数时会引起一些麻烦:

However, it caused some trouble when I tried to increase the integer:

def outer():
    a = 1
    def inner():
        a += 1 #or a = a + 1
        print a

>> UnboundLocalError: local variable 'a' referenced before assignment

为什么会发生这种情况,我该如何实现我的目标(增加整数)?

Why does this happen and how can I achieve my goal (increase the integer)?

推荐答案

Python 2的解决方法:

Workaround for Python 2:

def outer():
    a = [1]
    def inner():
        a[0] += 1
        print a[0]

这篇关于在python中修改内部函数的函数变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆