函数对象
函数对象指的是函数可以被当做“数据”来处理
函数名可以被引用
def index_1():print("from function index_1")res = index_1 # 让变量名res指向函数名res()# from function index_1
函数名可以当做函数的实参
def index_1():print("from function index_1") # 6.打印def index_2(a): # 2.将形参a与传入的index_1函数名绑定print("from function index_2") # 3.打印print(a) # 4.打印指向index_1函数的内存地址a() # 5.调用index_1()index_2(index_1) # 1.传入参数index_1函数名print(index_1) # 7.打印index_1函数的内存地址# from function index_2# <function index_1 at 0x7f94278c5ea0># from function index_1# <function index_1 at 0x7f94278c5ea0>
函数名可以当做函数的返回值
def index_1():print("from function index_1")return index_2 # 将函数名当做返回值def index_2():print("from function index_2")res = index_1() # 调用index_1函数,并将返回值index_2函数名指向给res# from function index_1print(res)# <function index_2 at 0x7fcad19bf400>print(index_2)# <function index_2 at 0x7fcad19bf400>res()# from function index_2
函数名可以作为容器类型的元素
def index_1():print("from function index_1")l = [1, 2, 3, index_1]print(l)# [1, 2, 3, <function index_1 at 0x7fabc58c5ea0>]l[-1]()# from function index_1
闭包函数
若内嵌函数包含对外部函数作用域(而非全局作用域)中变量的引用,那么该’内嵌函数’就是闭包函数,简称闭包(Closures)
闭与包
1.闭:定义在函数内部的函数
2.包:内部函数使用外层函数名称空间的“名字”
def outer():a = 1def inner():print('from function inner',a)return innerres = outer() # 调用outer()返回值赋值给resres()# from function inner 1
“闭”代表函数是内部的,“包”代表函数外’包裹’着对外层作用域的引用。因而无论在何处调用闭包函数,使用的仍然是包裹在其外层的变量。
闭包函数实际应用
一种是直接将值以参数的形式传入
def index(a):return aindex(1) # 需要重复传入index(1)index(1)
另外一种就是将值包给函数
def outer(a):def inner():return areturn innerres = outer(1) # 只需要传一次值res()res()res()
