鱼C论坛

 找回密码
 立即注册
查看: 2242|回复: 4

新人求教内嵌函数

[复制链接]
发表于 2015-11-29 11:59:30 | 显示全部楼层 |阅读模式

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

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

x
嵌套函数如下:
def test1(x):
    def test2(y):
        result = x + y
        return result
    return test2()

shell下访问始终提示少test2的y,求指导要如何运行该函数test1()????

>>> test1(2)
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    test1(2)
  File "C:\Users\Administrator\Desktop\ff.py", line 6, in test1
    return test2()
TypeError: test2() missing 1 required positional argument: 'y'

>>> test1(2)(3)
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    test1(2)(3)
  File "C:\Users\Administrator\Desktop\ff.py", line 6, in test1
    return test2()
TypeError: test2() missing 1 required positional argument: 'y'
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2015-11-29 14:09:14 | 显示全部楼层
修改了一下:
  1. def test1(x,y):
  2.     def test2(y):
  3.         result = x + y
  4.         return result
  5.     return test2(y)
复制代码
  1. >>> test1(1,2)
  2. 3
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-11-29 14:22:25 | 显示全部楼层
你的内嵌函数有个参数 而你在外部函数返回的时候是调用了内嵌函数,但是你的内嵌函数缺少参数,所以报错了,内嵌函数是一种编程范式,其内嵌函数作用域为外部函数内部,生存期则为其对象的生存期,所以内嵌函数扩大了外部函数的生存期。

def f1(x):
    def f2(y):
        r=x+y
        return r
    return f2(3)

print(f1(2))
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-11-29 17:05:52 | 显示全部楼层

谢谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-11-29 17:06:49 | 显示全部楼层
无名似名 发表于 2015-11-29 14:22
你的内嵌函数有个参数 而你在外部函数返回的时候是调用了内嵌函数,但是你的内嵌函数缺少参数,所以报错了 ...

明白了,谢谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-2-18 13:00

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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