python中嵌套函数的使用

1.python中的函数

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

输出为:

<function testfunc at 0x000001E1940E85E8>
hello,good boy

2.函数中定义函数

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()和testfunc2()在函数testfunc()之外是不能访问的。
例如:
在函数testfunc()之外调用func1()会报错:

NameError: name ‘func1’ is not defined

3.从函数中返回函数

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

在 if/else 语句中返回func1和 func2,而不是 func1() 和 func2()。当你把一对小括号放在后面,这个函数就会执行;如果不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。
当写下 tt=testfunc(1),testfunc()会被执行,函数 func1被返回了。
当写下tt()即testfunc()(),则输出:This is func1

4.将函数作为参数传给另一个函数

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

猜你喜欢

转载自blog.csdn.net/liulanba/article/details/114391274