Iterators, Generations, Generators, and Decorators in Python

1. Iterator

An iterator is a way to access the elements of a collection. Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only go forward and not backward, but that's okay, because people rarely go backwards in the middle of an iteration. In addition, one of the great advantages of iterators is that they do not require all elements of the entire iteration process to be prepared in advance. The iterator only evaluates an element when it iterates to the element, and before or after that, the element may not exist or be destroyed. This feature makes it especially suitable for traversing some huge or infinite collections, such as several G files

Features:

  1. The visitor does not need to care about the internal structure of the iterator, and only needs to continuously fetch the next content through the next() method
  2. A value in the collection cannot be accessed randomly, only sequentially from the beginning to the end
  3. You cannot go back halfway through the visit
  4. It is convenient to loop over large data sets and save memory

Generate an iterator:

 

>>> a = iter([1,2,3,4,5])
>>> a
<list_iterator object at 0x101402630>
>>> a.__next__()
1
>>> a.__next__()
2
>>> a.__next__()
3
>>> a.__next__()
4
>>> a.__next__()
5
>>> a.__next__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

 

2. Generatives and generators

List Compilation Format:

[exp for val in collection if condition]

[x*x for x in xrange(10) if x*x%2 == 0]

generator (generator):

method one:

(exp for val in collection if condition)

Method 2:
Using the yield keyword, the function containing the yield statement will be specially compiled into a generator.
Yield can be understood as return, but it does not exit, it just suspends, and executes from below yield when it resumes.

The difference between a generative and a generator:

The list display generation directly returns the result list of the expression. The surface generator is an object that contains the calculation reference to the expression result. The output
generator can be directly elected through the result loop without listing all the data at once. , of course, when you use it, it is listed to save memory usage.
Similar to the difference between range(1,10) xrange(1,10), but the type is different.

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @time   :2018/1/28 22:34
# @Author :FengXiaoqing
# @file   :production.py

a = [x*x for x in range(1,11) if x%2 ==0]
print (a)
print(type(a))

b = (x*x for x in range(1,11) if x%2 ==0)
print (b)
print(type(b))
for i in b:
    print(i)
print('#'*20)

def test(l):
    for i in l:
        yield i
        print("OK i = {0}".format(i))

m = test([1,2,3,4,5,6])
for i in m:
    print(i)
结果:
[4, 16, 36, 64, 100]
<class 'list'>
<generator object <genexpr> at 0x0000000002160D00>
<class 'generator'>
4
16
36
64
100
####################
1
OK i = 1
2
OK i = 2
3
OK i = 3
4
OK i = 4
5
OK i = 5
6
OK i = 6

3. Decorator

The role of the decorator:

A decorator is essentially a python function, which allows other utility functions to add extra functionality without any code changes. The return value of the decorator is also a function object. It is often used in scenarios with aspect requirements, such as: log insertion, performance testing, transaction processing, caching, permission verification and other scenarios. Decorators are an excellent design to solve this kind of problem. With decorators, we can extract a lot of identical code that has nothing to do with the function itself and continue to reuse it.
The role of the decorator is simply to say: it does not change the original function itself, but adds some extra functions before or after the function.
Scenario: Shopping on JD.com, after putting it in the shopping cart, a window pops up to let you log in to the user before checkout.

Decorator:

Before understanding the decorator, let's first understand a callable function
Description:
1. The method is used to detect whether the object can be called, and the batch that can be called is the method call using () brackets.
def a():
pass
callable(a)
2. For callable objects, it can be measured that the call fails in the actual call; but for non-callable objects, the call is definitely unsuccessful.
3. Class objects are all callable objects. Whether an instance object of a class is a callable object depends on whether the class defines a call method.

Decorator example:

#!/usr/bin/env python
import datetime

def hellow(fun):
    def preHello():
        print("########start##########“)
        fun()
        print("########end###########“)
    return preHello

Original method:

def startend(func):
    def start():
        print("#########start#############")
        func()
        print("#########end#############")
    return start
def hello():
    print("hello world!")
hello = startend(hello)
hello()

Improved usage:

def startend(func):
    def start():
        print("#########start#############")
        func()
        print("#########end#############")
    return start

@startend
def hello():
    print("hello world!")
hello()

Another instance:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/4/18 23:32
# @Author  : Feng Xiaoqing
# @File    : test.py
# @Function: -----------


def startEnd(author):
    def a(fun):
        def b(name):
            print("this author is {0}".format(author))
            print("start")
            fun(name)
            print("end")
        return b
    return a

@startEnd("fengxiaoqing")
def hello(name):
    print("hello {0}".format(name))

hello("fxq")

 result:

this author is fengxiaoqing
start
hello fxq
end

 

Guess you like

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