0923 notes

Closure function

Closure function: wrapped with the internal functions of both an internal function + variable closure function, and then back out through the return value of the form.

1. 内部函数可以引用外部函数的参数和局部变量,当外部函数返回了内部函数时,相关参数和变量都保存在返回的函数中。
2. 是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。

Examples

# print_msg是外围函数
def print_msg():
    msg = "I'm closure"

    # printer是嵌套函数
    def printer():
        print(msg)

    return printer


# 这里获得的就是一个闭包
closure = print_msg()
# 输出 I'm closure
closure()

msgIs a local variable, the print_msgfollowing functions should be executed would not exist. However, this nesting function reference variable, the local variable enclosed in a nested function, thus forming a closure.

普通打印url函数式
def s1(url):
    print(url)
    
f1('www.baidu.com')
f1('www.sougou.com')

闭包函数
def f1(url):
    def s1():
        print(url)  # 这里想打印的是url
    return s1     #函数对象


taobao = f1(‘www.sohu.com’)  # f1就是s1函数
taobao()

baidu = f1(‘www.baidu.com’)
baidu()

Decorator

Decorator: to increase the function function features an additional function

  1. Is itself decorative function to be decorated decoration function.
  2. Without changing the source code of the original function
  3. It does not change the original function is called

Decorators use:

  • Define a decorative function
  • Redefining your business function
  • Finally, call the function using the syntactic sugar

Getting started Usage: log printer unit

Decorative function: that is to increase the business function of a performance function, he printed the log process

# 这是装饰函数
def logger (func):  # add函数传值
    def wrapper(*arg,**kw):
        print('计算函数')
        # 真正执行的是这一行
        func(*arg,**kw)  # 相当于add函数
        
        print ('计算结束')
    return wrapper
 

Service function is a function of the body to be decorated, where two numbers are calculated, can be directly finished decorative syntactic sugar pointing function.

@ logger
def add(x,y):
    print (x+y)

The last execution function

add(200,50)

Output

计算函数
80
计算结束

Getting started Usage: timer

When performing a long calculation function

# 装饰函数
def timer(func):
    def wrapper(*arg,**kw):
        start = time.time()
        func(*arg,**kw)
        end = time.time
        
        time_z = end - start
        print(f'共花费{time_z}')
    return wrapper

# 业务代码
import time
@timer
def index():
    '''业务代码'''
    print('12121')
    time.sleep(1)

# index = timer(index)
index()
# 输出
'''
12121
共花费1.0008752346038818
'''

Two-decorator

  1. Used to decorate function is a function of the nature of his
  2. Without changing the source code of the function
  3. Do not change the function is called

Decorative template

def deco(func):
    def wrapper(*args,**kwargs):
        # 想要添加的功能
        res = func (*args,**kwargs)
        return res
    return wrapper

@ deco

@ Decorator syntax sugar

Guess you like

Origin www.cnblogs.com/fwzzz/p/11574609.html