Python函数

函数作用域LEGB


LEGB:L>E>G>B

L:local函数内部作用域
E:enclosing 函数内部与内嵌函数质检
G:global 全局作用域
B:build-in内置作用域

闭包

Closure:内部函数中对enclosing作用域的变量进行引用

__closure__ 属性
def test(passline):
    def cmp(score):
        if score >= passline:
            print "pass"
        else:
            print "failed"
    return cmp

f_100 = test(60)
f_150 = test(90)
f_100(89)
f_150(89)
def my_sum(*arg):
    return sum(arg)
def my_average(*arg):
    return sum(arg)/leg(arg)
def dec(func):
    def in_dec(*arg):
        print ('in dec arg=',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 return in_dec -> my_sum
#my_sum = in_dec(*arg)
my_sum = dec(my_sum)
print (my_sum(1,2,3))

python 的装饰器

装饰器其实就是对闭包的使用

def my_average(*arg):
    return sum(arg)/leg(arg)
def dec(func):
    def in_dec(*arg):
        print ('in dec arg=',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):
    return sum(arg)
#dec return in_dec -> my_sum
#my_sum = in_dec(*arg)
my_sum = dec(my_sum)
print (my_sum(1,2,3))
def deco(func):
    def in_deco(x,y):
        print ('in_deco')
        func(x,y)
    return in_deco
#deco(bar) -> in_deco
#bar = in_deco
#bar() in_deco() bar()
@deco
def bar(x,y):
    print ('in bar',x+y)
bar(1,2)

你可能感兴趣的:(Python函数)