理解Python:UnboundLocalE

2024-09-30 18:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经使用python一年多了,但是我对这个例子中的一些东西感到困惑:

def mul(x,y): return x*y

def setArg(f,a):
    def fx(*x):
        return f(*x,a)
    return fx

def test1():
    mul3=setArg(mul,3)

def test2():
    mul=4

def test3():
    mul=setArg(mul,3)

def test4():
    mu=setArg(mul,3)
    mul=mu

运行test1和test2可以正常工作,但运行test3和test4会产生以下错误: UnboundLocalError: local variable 'mul' referenced before assignment

我只能在testX中全局地重新定义mul吗? 为什么在python中如此? 使用python3.7


Tags: returnlocaldef错误例子fxtest1test2