鱼C论坛

 找回密码
 立即注册
查看: 87|回复: 1

关于函数闭包的困惑

[复制链接]
发表于 2025-2-8 00:06:21 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
关于函数闭包,我有以下2个问题不解:

1.我写的代码如下:
def outer():
    a = 123
    return a
    def inner(b):
        return b
return inner

result = outer()

result(1)
执行后出错,报错信息为
TypeError                                 Traceback (most recent call last)
Cell In[19], line 1
----> 1 result(1)

TypeError: 'int' object is not callable

我的困惑是:在外部函数outer()中,我定义了变量a并进行返回,但我并没有在内部函数inner()中对a进行引用,后面result(1)中的1应该赋值给内部函数中的b,这应该是没问题的,但为何会报错?

2.小甲鱼老师在讲解函数闭包中给了以下示例:
def outer():
    x = 0
    y = 0
    def inner(x1, y1):
        nonlocal x, y
        x += x1
        y += y1
        print(f"现在, x = {x}, y = {y}")
return inner

move = outer()

move(1, 2)

move(-2, 2)

小甲鱼老师通过在内部函数中声明一个nonlocal语句从而修改到外部函数中同名的参数.
我如果不想使用nonlocal语句修改外部函数中同名的参数,即删除nonlocal x,y这段代码,修改代码如下:
def outer():
    x = 0
    y = 0
    def inner(x1, y1):
        # nonlocal x, y
        x =x + x1
        y = y + y1
        print(f"现在, x = {x}, y = {y}")
return inner

move = outer()

move(1,2)
执行到move(1,2)时就会报错,报错信息如下:
UnboundLocalError                         Traceback (most recent call last)
Cell In[31], line 1
----> 1 move(1,2)

Cell In[29], line 6, in outer.<locals>.inner(x1, y1)
      4 def inner(x1, y1):
      5     # nonlocal x, y
----> 6     x += x1
      7     y += y1
      8     print(f"现在, x = {x}, y = {y}")

UnboundLocalError: local variable 'x' referenced before assignment

但如果我把内部函数中的x,y改成与外部函数中参数不一样的名字则不会报错了,代码如下:
def outer():
    x = 0
    y = 0
    def inner(x1, y1):
        # nonlocal x, y
       a = x+x1
        b = y+y1
        print(f"现在, x = {a}, y = {b}")
    return inner

move = outer()

move(1,2)
>>>现在, x = 1, y = 2

我的困惑是在内部函数中不通过使用nonlocal语句修改外部函数中参数的情况下,为何在内部函数中参数名与外部函数参数名一样就会报错,不同就不报错.希望大神帮忙指点一下!!!


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2025-2-8 00:06:36 | 显示全部楼层
关于函数闭包的困惑解答

1. 要解释你第一个问题的代码:
def outer():
    a = 123
    return a
    def inner(b):
        return b
return inner

result = outer()
result(1)
在这段代码中,outer() 函数返回的是变量 a,即整数 123,而不是内部函数 inner。所以调用 result(1) 就相当于 123(1),会导致 TypeError: 'int' object is not callable

如果你希望返回内部函数 inner,应该修改代码如下:
def outer():
    a = 123
    def inner(b):
        return b
    return inner

result = outer()
print(result(1))  # 输出 1

2. 来看你的第二个问题:
def outer():
    x = 0
    y = 0
    def inner(x1, y1):
        # nonlocal x, y
        x = x + x1
        y = y + y1
        print(f"现在, x = {x}, y = {y}")
    return inner

move = outer()
move(1, 2)
这里报错的原因是,在没有使用 nonlocal 关键字的情况下,Python 认为在内部函数 inner 中的 xy 是局部变量。由于局部变量尚未赋值就被引用,所以报了 UnboundLocalError

当变量名与外部函数中的变量不同时,不会有这个问题,因为这时 xy 不再是局部变量,而是内部函数中的新变量。你可以把内部函数修改成:
def outer():
    x = 0
    y = 0
    def inner(x1, y1):
        a = x + x1
        b = y + y1
        print(f"现在, x = {a}, y = {b}")
    return inner

move = outer()
move(1, 2)  # 输出 "现在, x = 1, y = 2"

总结一下:
  • 如果需要在内部函数中修改外部函数中的变量,需要使用 nonlocal 关键字。
  • 如果不想用 nonlocal 关键字,就需要使用不同的变量名来避免冲突。


希望以上解释能帮你解决对于函数闭包的困惑!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-2-24 01:31

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表