0923 Class Summary

Closure function

Defined closure function

Closure: closing a closed (function of the internal function), is a package comprising (a reference to the inner function rather than a variable outer scope of global scope).

Closure means: a function of an internal function of the external reference, and not scope of global scope.

Examples closure function

import requests


def outter(url):
    def get():
        response = requests.get(url)
        print(f"done: {url}")
    return get

baidu=outter('https://www.baidu.com')
python = outter('https://www.python.org')

baidu()
baidu()

python()
python()   

Layer decorator

Decorative definition

Device refers to the tool, and the function of the program is to have a functional tool, it refers to a decorator to add additional functionality to the decorator object. Therefore, the definition of decorator is the definition of a function, but the function of the function is used to add additional functionality to other functions.

Decorator principle

Achieve decorator must follow two principles:

  1. Does not modify the source code of an object to be decorated
  2. Call does not modify the manner of decorative objects

Layer decorator template

def outter(func):
    def innter(*args,**kwargs):
        # 代码块  需要实现的功能
        res = func(*args,**kwargs)
        return res
    return innter

Three decorator

Layer Layer outer decorator decorator is then wrapped a function, a parameter is passed Layer decorator

def sanceng(engine):
    def outter(func):
        def wrapper(*args, **kwargs):  # wrapper是未来要运行的函数
            # 加功能

            res = func(*args, **kwargs)  # func是被装饰的函数
            return res
        return wrapper
    return outter

Iterator introduced

Iterables defining: __ iter__ method is called iterables

May iterator defining: __ iter__ and __ next__ method called iterator

Guess you like

Origin www.cnblogs.com/faye12/p/11573188.html