gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:39 27 4
gpt4 key购买 nike

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

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.

关于python - 如何在另一个函数中调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23188207/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com