Skip to main content
 首页 » 编程设计

python之如何在另一个函数中调用函数

2025年05月04日17mayingbao

如果我有两个函数,(一个在另一个里面);

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

如何调用test2?

请您参考如下方法:

也可以这样调用:

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.