从小白到小黑 python学习之旅 日常总结 16(函数对象和闭包)

函数对象

 

 

精髓:可以把函数当成变量去用

# func=内存地址
def func():
    print('from func')


1、可以赋值

 

def func():
    print('from func')
f=func
f()
#from func

 


2、可以当做函数当做参数传给另外一个函数
def func():
    print('from func')
def foo(x): # x = func的内存地址
    print(x) # print(func)
    x() #func()

foo(func) # foo(func的内存地址)
#<function func at 0x00000000026CE160>
#from func

 


3、可以当做函数当做另外一个函数的返回值
def func():
    print('from func')


def foo(x):  # x=func的内存地址
    return x  # return func的内存地址


res = foo(func)  # foo(func的内存地址)
print(res)  # res=func的内存地址

res()
#<function func at 0x00000000026DE160>
#from func

 


4、可以当做容器类型的一个元素
def func():
    print('from func')
l=[func,]
l[0]()
#from func

dic={'k1':func}
print(dic)
#{'k1': <function func at 0x00000000026CE160>}
dic['k1']()
#from func



函数嵌套

1、函数的嵌套调用:在调用一个函数的过程中又调用其他函数
def max2(x,y):
    if x > y:
        return x
    else:
        return y


def max4(a,b,c,d):
    # 第一步:比较a,b得到res1
    res1=max2(a,b)
    # 第二步:比较res1,c得到res2
    res2=max2(res1,c)
    # 第三步:比较res2,d得到res3
    res3=max2(res2,d)
    return res3

res=max4(1,2,3,4)
print(res)
#4

 


2、函数的嵌套定义:在函数内定义其他函数
def f1():
    def f2():
        pass

 

 




闭包函数



基于函数对象的概念,可以将函数返回到任意位置去调用,但作用域的关系是在定义完函数时就已经被确定了的,与函数的调用位置无关。

重点

      闭包函数=名称空间与作用域+函数嵌套+函数对象
核心点:名字的查找关系是以函数定义阶段为准


二:什么是闭包函数


"闭"函数指的该函数是内嵌函数
"包"函数指的该函数包含对外层函数作用域名字的引用(不是对全局作用域)


闭包函数:名称空间与作用域的应用+函数嵌套


#f2()是闭包函数
def f1():
    x = 33333333333333333333
    def f2():   
        print(x)
    f2()


x = 11111


def bar():
    x = 444444
    f1()


def foo():
    x = 2222
    bar()


foo()
#33333333333333333333

 


闭包函数:函数对象


def f1():
    x = 33333333333333333333

    def f2():
        print('函数f2:', x)

    return f2 


f = f1() #f2


def foo():
    x = 5555
    f() # f2()


foo() #f2()
#函数f2: 33333333333333333333


三:为何要有闭包函数=》闭包函数的应用

两种为函数体传参的方式


方式一:直接把函数体需要的参数定义成形参

def f2(x):
    print(x)

f2(1)
#1

 


方式二:

 


def f1(x):  # x=3

    def f2():
        print(x)

    return f2


x = f1(3)
print(x)
#<function f1.<locals>.f2 at 0x00000000026CE3A0>
x()
#3

 



















 

posted @ 2020-03-20 17:46  It's_cool  阅读(126)  评论(0)    收藏  举报