我试图调用一个嵌套的函数。
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谢谢你的帮助!
发布于 2013-12-25 14:25:00
您必须返回函数对象;否则,function2只是function1中的另一个局部变量:
def function1():
#code here
def function2():
return foo
return function2
def function3():
x = function1()() # calls function2, returned by function1()调用function1()返回function2对象,然后立即调用该对象。
演示:
>>> 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注意调用foo()是如何返回函数对象的。
发布于 2013-12-25 14:25:26
要实现这一点,您必须从function2返回function1,然后像这样从function3调用function2
def function1():
#code here
def function2():
return #variable
return function2
def function3():
x = function1()
print x()或者,与其将function2存储在x中,您可以简单地
def function3():
print function1()()https://stackoverflow.com/questions/20773719
复制相似问题