The use of nested functions in python

1.Functions in python

def testfunc():
    return "hello,good boy"
cpufc=testfunc#将一个函数赋值给一个变量
print(cpufc)
print(cpufc())#调用函数

The output is:

<function testfunc at 0x000001E1940E85E8>
hello,good boy

2. Define the function in the function

def testfunc():
    def func1():
        return "This is func1"
    def func2():
        return "This is func2"

    print(func1())
    print(func2())
    print("Now you are back in testfunc()")
testfunc()
This is func1
This is func2
Now you are back in testfunc()

testfunc1() and testfunc2() are not accessible outside the function testfunc().
For example:
calling func1() outside the function testfunc() will report an error:

NameError: name ‘func1’ is not defined

3. Return a function from a function

def testfunc(n):
    print("Now you are in testfunc()")
    def func1():
        return "This is func1"
    def func2():
        return "This is func2"
    return func1 if n==1 else func2
tt=testfunc(1)
print(tt)
print(tt())
#Now you are in testfunc()
#<function testfunc.<locals>.func1 at 0x000001FDE78EBCA8>
#This is func1

In the if/else statement, return func1 and func2 instead of func1() and func2(). When you put a pair of parentheses after it, this function will execute; if you don't put the parentheses after it, it can be passed around, and can be assigned to other variables without executing it.
When writing tt=testfunc(1), testfunc() will be executed and the function func1 will be returned.
When writing tt() that is testfunc()(), the output is: This is func1

4. Pass a function as a parameter to another function

def func1():
    return "This is func1"
def func2(func):
    print("This is func2")
    print(func)
func2(func1)
print("*"*10)
func2(func1())

# This is func2
# <function func1 at 0x0000020F9AC88048>
# **********
# This is func2
# This is func1

Guess you like

Origin blog.csdn.net/liulanba/article/details/114391274