@knight
2016-01-14T22:01:36.000000Z
字数 2339
阅读 2313
python
LEGB:L>E>G>B
判断一个学生是否及格。
#!/usr/bin/env python
# coding=utf-8
passline = 60
def func(val):
#passline = 90
if val >= passline:
print ("pass")
else:
print ("failed")
def in_func():
print (val)
def Max(val1, val2):
return max(val1,val2)
func(89)
通过上面例子,了解函数作用域和LEGB规则
Closure: 内部函数中对enclosing作用域的变量进行引用。
函数实质与属性
1. 函数是一个对象
2. 函数执行完成后内部变量回收
3. 函数属性
4. 函数返回值
#!/usr/bin/env python
# coding=utf-8
passline = 60
def func(val):
#passline = 90
print ('%x'%id(val))
if val >= passline:
print ("pass")
else:
print ("failed")
def in_func():
print (val)
in_func()
return in_func
f = func(89)
f()
print (f.__closure__)
使用闭包
#!/usr/bin/env python
# coding=utf-8
passline = 60
def func_150(val):
passline = 90
if val >= passline:
print ('pass')
else:
print ('failed')
def func_100(val):
passline = 60
if val >= passline:
print ('pass')
else:
print('failed')
def set_passline(passline):
def cmp(val):
if val >= passline:
print('pass')
else:
print ('failed')
return cmp
f_100 = set_passline(60)
print type(f_100)
print (f_100.__closure__)
f_100(89)
f_100(59)
f_150 = set_passline(90)
f_150(89)
闭包作用
1. 封装
2. 代码复用
#!/usr/bin/env python
# coding=utf-8
def my_sum(*arg):
# if len(arg) == 0:
# return 0
# for val in arg:
# if not isinstance(val, int):
# return 0
return sum(arg)
def my_average(*arg):
# if len(arg) == 0:
# return 0
# for val in arg:
# if not isinstance(val, int):
# return 0
return sum(arg)/len(arg)
# 使用闭包完成
def dec(func):
def in_dec(*arg):
if len(arg) == 0:
return 0
for val in arg:
if not isinstance(val, int):
return 0
return func(*arg)
return in_dec
my_sum = dec(my_sum)
my_average = dec(my_average)
print (my_sum(1,2,3,4,5))
print (my_sum(1,2,3,4,5, '6'))
print (my_average(1,2,3,4,5))
print (my_average())
#!/usr/bin/env python
# coding=utf-8
def dec(func):
print ("call dec")
def in_dec(*arg):
if len(arg) == 0:
return 0
for val in arg:
if not isinstance(val, int):
return 0
return func(*arg)
return in_dec
@dec
def my_sum(*arg):
# if len(arg) == 0:
# return 0
# for val in arg:
# if not isinstance(val, int):
# return 0
return sum(arg)
@dec
def my_average(*arg):
# if len(arg) == 0:
# return 0
# for val in arg:
# if not isinstance(val, int):
# return 0
return sum(arg)/len(arg)
print (my_sum(1,2,3,4,5))
print (my_sum(1,2,3,4,5, '6'))
print (my_average(1,2,3,4,5))
print (my_average())
装饰器等价于闭包调用,使用语法糖可以隐式的调用。
call dec
call dec
15
0
3
0
def deco(func):
def in_deco(x,y):
print ('in deco')
func(x,y)
print ('call deco')
return in_deco
# deco(bar) -> in_deco
# bar = in_deco
# bar() in_deco() bar()
@deco
def bar(x,y):
print ('in bar', x+y)
print (type(bar))
bar(1,2)