Discuss / Python / 请问有人知道这样为什么不行吗

请问有人知道这样为什么不行吗

Topic source
def lazy_sum(*args):
    ax = 0
    def sum():

        for n in args:
            ax = ax + n
        return ax
    return sum

f = lazy_sum(1, 3, 5, 7, 9)
print (f())

就是把教程开头的那个例子的ax = 0 移到 sum外面了

会报如下错误: UnboundLocalError: local variable 'ax' referenced before assignment

按照教程里: 在这个例子中,我们在函数lazy_sum中又定义了函数sum,并且,内部函数sum可以引用外部函数lazy_sum的参数和局部变量,当lazy_sum返回函数sum时,相关参数和变量都保存在返回的函数中

那感觉这样应该不会有错呀

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]
def lazy_sum(*args):
    ax = 0
    def sum():
        local ax
        for n in args:
            ax = ax + n
        return ax
    return sum

这是Python解释器的一个小问题,需要明确告诉解释器ax已经申明

posroachips

#3 Created at ... [Delete] [Delete and Lock User]

老师,我照着您给的代码打到local ax这一句的时候提示SyntaxError: invalid syntax……

廖雪峰

#4 Created at ... [Delete] [Delete and Lock User]

python >= 3

我的解释器是3.5.0的,但是换成local ax依然不行,还是提示语法错误,后来百度了下,换成“nonlocal ax”就可以了(当然“global ax”全局变量也可以),nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量。链接在这里:http://www.jb51.net/article/57677.htm def lazy_sum(*args): ax = 0 def sum1() nonlocal ax for n in args: ax = ax + n return ax return sum


  • 1

Reply