如何在另一个函数中调用函数?

时间:2014-04-20 22:15:53

标签: python python-2.7 python-3.x

如果我有两个功能,(一个在另一个内部);

def test1():
    def test2():
        print("test2")

如何致电test2

3 个答案:

答案 0 :(得分:3)

def test1():
  def test2():
    print "Here!"
  test2() #You need to call the function the usual way

test1() #Prints "Here!"

请注意test2功能在test1之外无法使用。例如,如果您尝试稍后在代码中调用test2(),则会出现错误。

答案 1 :(得分:3)

您也可以这样称呼它:

def test1():
    text = "Foo is pretty"
    print "Inside test1()"
    def test2():
        print "Inside test2()"
        print "test2() -> ", text
    return test2

test1()() # first way, prints "Foo is pretty"

test2 = test1() # second way
test2() # prints "Foo is pretty"

让我们看看:

>>> Inside test1()
>>> Inside test2()
>>> test2() ->  Foo is pretty

>>> Inside test1()
>>> Inside test2()
>>> test2() ->  Foo is pretty

如果您不想致电 test2()

test1() # first way, prints "Inside test1()", but there's test2() as return value.
>>> Inside test1()
print test1()
>>> <function test2 at 0x1202c80>

让我们变得更加努力:

def test1():
    print "Inside test1()"
    def test2():
        print "Inside test2()"
        def test3():
            print "Inside test3()"
            return "Foo is pretty."
        return test3
    return test2

print test1()()() # first way, prints the return string "Foo is pretty."

test2 = test1() # second way
test3 = test2()
print test3() # prints "Foo is pretty."

让我们看看:

>>> Inside test1()
>>> Inside test2()
>>> Inside test3()
>>> Foo is pretty.

>>> Inside test1()
>>> Inside test2()
>>> Inside test3()
>>> Foo is pretty.

答案 2 :(得分:0)

您不能,因为test2test1()返回后停止存在。要么从外部函数返回它,要么只从那里调用它。