闭包
在一个外函数中定义了一个内函数,内函数里运用了外函数的临时变量,并且外函数的返回值室内函数的引用.这样就够成了一个闭包.一般情况下,在我们认知当中,如果一个函数结束,函数的内部所有东西都会释放掉,还给内存,局部变量都会消失,但是闭包是一种特殊情况,如果外函数在结束的时候发现有自己的临时变量将来会在内部函数中用到,就把这个临时变量绑定给了内部函数,然后自己再结束.
闭包和装饰模式 相辅相成
函数后加()为执行的意思 不加()为传递引用的意思
- #普通闭包
- def outter(fun):
- def inner():
- print('123')
- fun()
- print('456')
- return inner
- def index():
- print('woshi index')
- ind=outter(index)
- ind()
执行命令得
- 123
- woshi index
- 456
装饰器闭包
- #装饰器闭包
- def outter(fun):
- def inner():
- print('123')
- fun()
- print('456')
- return inner
- @outter
- def index():
- print('woshi index')
- index()
执行命令得
- 123
- woshi index
- 456
练习
火锅点菜结账系统
- def xuebi(fun):
- def caidan():
- print('雪碧 5元')
- return fun()+5
- return caidan
- def yangrou(fun):
- def caidan():
- print('羊肉 80元')
- return fun()+80
- return caidan
- @xuebi
- @yangrou
- def guodi():
- print('三鲜锅 50元')
- return 50
- price=guodi()
- print('总消费',price)
执行命令得
- 雪碧 5元
- 羊肉 80元
- 三鲜锅 50元
- 总消费 135
1-4分别加9得出结果分别添加到列表中
- list=[]
- def outter():
- def inner(y):
- lam=lambda x,y:x+y
- for x in range(1,5):
- list.append(lam(x,y))
- return inner
- out=outter()
- out(9)
- print(list)
执行命令得
- [10, 11, 12, 13]
1-4分别乘9得出结果添加到列表中
- list=[]
- def outter(fun):
- def inner(y):
- for x in range(1,5):
- list.append(fun(x,y))
- return inner
- def suan(x,y):
- return x*y
- out=outter(suan)
- out(9)
- print(list)
执行命令得
- [9, 18, 27, 36]
Python3特性 str转换为函数eval()实现带参函数fun(x,y)
- x=int(input('请输入第一个数字:'))
- y=int(input('请输入第二个数字:'))
- fun=eval(input('请输入一个函数:'))
- ret=fun(x,y)
- print(ret)
- print(type(fun))
- print(type(ret))
执行命令得
- 请输入第一个数字:6
- 请输入第二个数字:4
- 请输入一个函数:lambda x,y:x*y
- 24
- <class 'function'>
- <class 'int'>