我正在尝试调用嵌套的函数。
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
感谢您的帮助!
答案 0 :(得分:2)
你必须返回函数对象; 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()
如何返回一个函数对象。
答案 1 :(得分:1)
要实现这一目标,您必须从function2
返回function1
,然后从function2
拨打function3
def function1():
#code here
def function2():
return #variable
return function2
def function3():
x = function1()
print x()
或者,您可以简单地执行
,而不是将function2
存储在x
中
def function3():
print function1()()