![](/img/trans.png)
[英]How to use returned result from inner function as a parameter in the outer function?
[英]3 layer function and use the inner most one to output the result
这更像是脑筋急转弯,而不是实际行动。 我创建了一个3层函数,彼此堆叠。 我不能告诉python仅通过最内部的函数将3个给定的数字参数加在一起,有人可以帮忙吗?
def first(x):
def second(y):
def third(z):
return(x+y+z)
return third
third1 = first(1)
third2 = second(2)
....... get stuck here .......
您需要每个函数返回其“子”函数,然后保留对该函数的引用,然后在下一步中进行调用-类似:
def first(x):
print(x)
def second(y):
print(y)
def third(z):
print(z)
return(x+y+z)
return third
return second
two = first(1)
three = second(2)
print(three(3))
这段代码的问题是second
函数不能被调用。 它与尝试调用它的代码不在同一词法范围内。
有效的示例:
def first(x):
def second(y):
def third(z):
return x+y+z
return third
return second
f = first(1)
s = f(2)
print s(4) # 6
就像second
需要返回third
, first
需要返回second
。
def first(x):
def second(y):
def third(z):
return(x+y+z)
return third
return second
此外,您不能直接调用second
,因为那是first
本地名称。 您需要调用first
的返回值:
f1 = first(1) # f1 is second wrapped around x == 1
f2 = f1(2) # f2 is third wrapped around x == 1 and y == 2
f3 = f2(3) # f3 is 1 + 2 + 3 == 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.