Function Decorators and Closures

I have a deeper understanding of the closure of js before, and look back at python.

装饰器:
    1.  函数装饰器
    2.  类装饰器

1) Decorator: A decorator is a callable object whose parameter is another function (the decorated function). A decorator may process the decorated function and return it, or replace it with another function or callable object.

#装饰器 原理是吧函数替换成另一个函数,所以夏敏的target()里面的print()没有执行
def deco(func):
    def inner():
        print('runngin inner()')

    return inner

@deco
def target():
    print('running target()')

target()
###############等同如下:
def deco(func):
    def inner():
        print('runngin inner()')

    return inner

def target():
    print('running target()')

f = deco(target)
f() 
###########################
#所以要想print()的都打印出来。修改如下:
def deco(func):
    def inner():
        func()
        print('runngin inner()')
    return inner

Closure:

def add_one():
    books = []

    def newbook(b):
        books.append(b)
        return books
    return newbook


add = add_one()
print(add('lubinxun')) #['lubinxun']
print(add('xiyouji'))  #['lubinxun', 'xiyouji']

write picture description here
For immutable types such as numbers, strings, and tuples, which can only be read and cannot be updated, updating them in the closure will cause the interpreter to implicitly create local variables, so that they cannot become free variables, so they will not Save to closure. In the above example, it is a shared mutable object - a list, so there is no problem. The solution to immutable types that cannot be free variables is: (python3) use the nolocal declaration.

def make_averager():
    count = 0
    total = 0

    def avg(new_value):
        nonlocal  count,total
        count +=1
        total +=new_value
        return total/count
    return avg

avg = make_averager()
print(avg(1)) #1.0
print(avg(2))  #1.5
print(avg(3))  #2

Problems with variables in closures, variables in for loops

def count():
    fs = []
    for i in range(1, 4):
        def f(a=i):
            return a*a
        fs.append(f)
    return fs

f1, f2, f3 = count()
print(f1(), f2(), f3())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325468631&siteId=291194637