第一个函数为什么错了?
>>> def test1(x):def test2(a):
return a
print(x)
return x
>>> test1(1)(2)
1
Traceback (most recent call last):
File "<pyshell#1222>", line 1, in <module>
test1(1)(2)
TypeError: 'int' object is not callable
>>> def test(x):
return x
>>> test(1)
1 你得返回test2才能调用它呀 def test1(x):
def test2(a):
return a
print(x)
return test2
print(test1(1)(2))
正如楼上所说,你应该返回一个函数体,才能 test1(1)(2) 这样两个括号的调用
否则因为你调用 test1(1) 的返回值是 x,即此时 x 为 test1 传入的 1 ,则返回结果 1 后你对这个值进行调用
即你调用 test1(1)(2) 相当于这样调用1(2),而 1 为 int 型,肯定无法进行调用而导致报错
所以你将 return 那更为内嵌函数即可,参考代码:
def test1(x):
def test2(a):
return a
print(x)
return test2
print(test1(1)(2))
你代码更改成这样,调用 test1(1)(2) 就相当于调用 test2(2),即可成功调用
Twilight6 发表于 2021-6-4 19:05
正如楼上所说,你应该返回一个函数体,才能 test1(1)(2) 这样两个括号的调用
否则因为你调用 test1(1) ...
我在尝试对内嵌函数做出各种可能,然后看看效果。关于这个函数,我本意没想让闭包函数发挥效果...
的确,如此下来只要执行外部函数,不输入闭包函数的参数即可。是我打多了。谢谢
页:
[1]