day 13 are summarized (the closure function, decorators, iterator)

First, the closure function

1. What is a closure?

  • 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.
def outter():
    x = 1

    def inner():
        print(x)
    return inner


f = outter()


def f2():
    x = 2
    f()


f2()

1.1 two types of functions parameter passing mode

Method 1: formal parameters

def func(x):
    print(x)


func(1)
func(1)
func(1)
1
1
1

Second way: packet function

def outter(x):
    x = 1

    def inner():
        print(x)
    return inner


f = outter(1)
f()
f()
f()
# 查看闭包的元素
print(F"f.__closure__[0].cell_contents: {f.__closure__[0].cell_contents}")
1
1
1
f.__closure__[0].cell_contents: 1

2, application of closure function

Significance closure package: the function returns an object, not just a function object, outside the scope function also wrapped in a layer, which makes the function calls regardless of where, preferentially the outer layer wrapped their scope.

Application: delay calculation (turns out that we are mass participation, and now we are wrapped up), reptiles fields.

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()
done: https://www.baidu.com
done: https://www.baidu.com
done: https://www.python.org
done: https://www.python.org

Second, the decorator

1, no reference decorator

1.1 What is a decorator?

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.

have to be aware of is:

  • Decorator itself can actually be any object that can be called
  • Ornamented objects can be any callable objects

1.2 Why use a decorator?

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

Decorator in fact, add new features to the object to be decorated under the premise of following the above two principles.

1.3 Decorative template (double decorator)

def outter(func):
    def wrapper(*args, **kwargs):  # wrapper是未来要运行的函数
        # 加功能
        res = func(*args, **kwargs)  # func是被装饰的函数
        return res

    return wrapper

The first parameter passing mode: change the way calls

mport time


def index():
    print('welcome to index')
    time.sleep(1)


def time_count(func):
    start = time.time()
    func()
    end = time.time()
    print(f"{func} time is {start-end}")


time_count(index)
welcome to index
<function index at 0x102977378> time is -1.000748872756958

The second parameter passing mode: packet function - Outsourcing

import time


def index():
    print('welcome to index')
    time.sleep(1)


def time_count(func):
    # func = 最原始的index
    def wrapper():
        start = time.time()
        func()
        end = time.time()
        print(f"{func} time is {start-end}")
    return wrapper

# f = time_count(index)
# f()


index = time_count(index)  # index为被装饰函数的内存地址,即index = wrapper
index()  # wrapper()
welcome to index
<function index at 0x102977730> time is -1.0038220882415771

2, reference decorator

No parameters set decorator only two layers, this section will tell a three-set decorator - there is a reference decorator, but now let's implement a registered user login decorators.

Three decorator template

def sanceng(engine):
    def outter(func):
        def wrapper(*args, **kwargs):  # wrapper是未来要运行的函数
            # 加功能
            print(engine)
            res = func(*args, **kwargs)  # func是被装饰的函数
            return res

        return wrapper

    return outter

Third, the iterator

Iterator: Tools iteration. Iteration is upgrading, such as your grandfather gave birth to your father, your father gave birth to you, iteration can be said to be repeated, and repeated every time but are based on the results of the last. Such as iterative development of the computer is updated based on a version of the software. The following code is not iterative, it's just a simple repetition.

1, iterables

to sum up

Iterable object: Python built-in str, list, tuple, dict, set, file are iterable.

Features:

  1. Built-in __iter__object methods can be called iterations.

2, iterator object

Only strings and lists are dependent on the value of the index, while other iterable are not dependent on the value of the index. So we have to find a way to make other iterable does not depend on the index value.

Concept before finding this method, we first give an iterator object: iterable object to perform __iter__the return value obtained by the method. And the object will have an iterative __next__method.

to sum up

Iterator object: object execution may iterative __iter__method to get the value that is returned iterator object.

Features:

  1. Built-in __next__method, the method is performed will get a value iterator object
  2. Built-in __iter__method, the implementation of which will get the iterator itself
  3. Iterator object file itself.

Disadvantages:

  1. Value of trouble, can take a one, and only later taken, take the value gone
  2. You can not be used len () method to get the length

3, for circulation principle

The for loop called the iterator loop must be in the iterative object.

lis = [1, 2, 3]
for i in lis:
    print(i)
1
2
3

Because iterator use __iter__an object or after the iterator itself, and therefore not considered in the for loop is an iterative iterator object or objects.

Due to the use iterables __iter__become a target after the iterator method, the iterator object occupies only a small memory space, he is only using __next__only spit out one by one value. As lis = [1,2,3,4,5,...]the equivalent of a an egg, while lis = [1,2,3,4,5,...].__iter__the equivalent of an old hen, if you need an egg, only __next__you can.

Python3 in

print(range(10))  # range(0, 10)

Guess you like

Origin www.cnblogs.com/mgytz/p/11545033.html