Python装飾器(閉包)

11881 ワード

(一)関数作用域LEGB
LEGB:L>E>G>B
L:local関数内部の役割ドメイン
E:enclosing関数内部と埋め込み関数間
G:globalグローバル役割ドメイン
B:build-in内蔵役割ドメイン(python解釈器がデフォルトでインポートしたリスト、tupleなどの変数)
変数を検索すると、まず関数の内部、次にenclosing、次にglobal、最後にbuild-inになります.
passline=60
def func(val): #                  ,       val      
    passline=90 #         
    if val>=passline: #      passline,         
        print('pass')
    else:
        print('faild')
    def in_func():  #(val,)             ,         ,    。
        print(val) #   val     in_func           ,     encloding  ,    func   val
    in_func()
def Max(val1,val2):
    return  max(val1,val2)#   max            ,            ,   build-in    
print(Max(80,100))
func(89)
 
  

(二)函数装饰器之闭包

Closure:      enclosing          
1,       (          )
2,            (          ,      ,        )
3,    
4,     
       enclosing  ,            ,        ,         ,         
 
  
def set_passline(passline):
    print('%x' % id(passline))
    def cmp(val):
        if val>=passline:
            print('Pass')
        else:
            print('faild')
    return  cmp

f_100=set_passline(60)
f_150=set_passline(90)
print(f_100)
print(f_150)
print(f_100.__closure__) #                ,       ,    
print(f_150.__closure__)
f_100(89)
f_150(89)
5bc40930
5bc40cf0
.cmp at 0x0000016956C5E950>
.cmp at 0x0000016956C5E9D8>
(,)
(,)
Pass
faild
    :  ,    
 
  
def my_sum(*arg):
    print(arg)
    return sum(arg)
def my_average(*arg):
    return sum(arg)/len(arg)
def dec(func):
    def in_dec(*arg):#    in_dec,  func   in_dec    ,        in_dec   ,      my_sum()
        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) #   fuc         
    return in_dec
#  dec  ,  in_dec  ,in_dec    my_sum  
#          ,         my_sum=in_dec(*arg)
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,'3'))
print(my_average(1,2,3,4,5))
print(my_average())

(三)python装飾器
1,         
2,        
3,                 
4,    @deco
 
  
def dec(func):
    print('call dec')
    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) #   fuc         
    return in_dec
@dec#my_sum=dec(my_sum)
def my_sum(*arg):#my_sum=in_dec
    print(arg)
    return sum(arg)
print(my_sum(1,2,3,4,5))
def my_average(*arg):
    return sum(arg)/len(arg)
装飾器の詳細:
 
  
def deco(func):
    def in_deco(x,y):
        print('in deco')
        func(x,y)
    print('call deco')
    return in_deco
#       @deco ,   deco  ,  bar      ,    deco  in_deco
# bar=in_deco  bar  in_deco
#   bar()  ,    in_deco(), in_deco     ,          bar()  
@deco
def bar(x,y):
    print('in bar',x+y)
print(type(bar))
bar(1,3)