[英]How to call a function that is nested in python
I'm trying to be able call a function that is nested. 我试图能够调用嵌套的函数。
def function1():
#code here
def function2():
return #variable
def function3():
x = #the variable that is returned in function2
# I'm not sure how to get it to equal the variable that was returned in function2
Thanks for the help! 谢谢您的帮助!
You would have to return the function object; 您将必须返回函数对象; function2
is just another local variable inside function1
otherwise: function2
只是内部的另一个局部变量function1
,否则:
def function1():
#code here
def function2():
return foo
return function2
def function3():
x = function1()() # calls function2, returned by function1()
Calling function1()
returns the function2
object, which is then called immediately. 调用function1()
返回function2
对象,然后立即调用该对象。
Demo: 演示:
>>> def foo(bar):
... def spam():
... return bar + 42
... return spam
...
>>> foo(0)
<function spam at 0x10f371c08>
>>> foo(0)()
42
>>> def ham(eggs):
... result = foo(eggs + 3)()
... return result
...
>>> ham(38)
83
Note how calling foo()
returns a function object. 注意调用foo()
如何返回一个函数对象。
To make that happen, you have to return function2
from function1
and then call function2
from function3
like this 要做到这一点,你必须返回function2
从function1
,然后调用function2
从function3
这样
def function1():
#code here
def function2():
return #variable
return function2
def function3():
x = function1()
print x()
Or, instead of storing function2
in x
, you can simply do 或者,您可以简单地执行以下操作,而不是将function2
存储在x
def function3():
print function1()()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.