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

标签 python python-2.7 python-3.x

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

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/

相关文章:

python - 内置模板标签似乎破坏了 i18n

python - 从哪个 Python 3 API 开始?

python - 为什么这个表达式返回 10 而我期望它返回 15?

python - 按列迭代 3D 列表

python - pandas dataframe 按 nan 数删除列

python - 从两个矩阵乘积的条目填充 4d 数组的有效方法

python - 在 pandas 中过滤、分组和计数?

python - 如何使用参数上的自定义标记在 pytest 中选择测试子集

python - 使用正则表达式来匹配我的字符串内容?

python - 将带有字典的 Python List 转换为一个字典的最快方法