如何调用嵌套在python中的函数

时间:2013-12-25 14:20:44

标签: python function 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

感谢您的帮助!

2 个答案:

答案 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()()