Python basis (seven) closures and decorator

Defined closure

  1. Function is nested within the closure function.
  2. Closures must be a variable function of the outer layer of the inner function (non-global variable) reference.

Closure formats:

def func():
    lst=[]
    def inner(a):
        lst.append(a)
        return lst
    return inner

ret=func()
print(ret(100))         #[100]
print(ret(200))         #[100, 200]             

The method of determination is not the closure:

# 判断一个函数是不是闭包 == 闭包函数有没有自由变量
print(函数名.__code__.co_freevars)

Application package closure:

1, to ensure data security.

2, the nature of the decorator.

3.1 decorator basic format

Decorator: without changing the original function of the internal code before and after the function perform a certain function

def func(arg):
    def inner():
        print('alex')
        v=arg()
        print('wusir')
        return v
    return inner
#第一步:执行index并将下面的函数当作参数传递:相当于func(index)
#第二步:将func的返回值重新赋值给下面的函数 相当于:index=func(index)
@func
def index():
    print(123)
    return 666

print(index)

Written form decorator

def 外部函数(参数):
    def 内部函数(*args,**kwargs):
        return 参数(*args,**kwargs)
    return(内层函数)
@外层函数
def index()
    pass


inde()

Guess you like

Origin www.cnblogs.com/llwwhh/p/11099638.html