Iterators and generators in Python, as well as decorations

Source: Internet
Author: User
Tags closure

One, iterator

It is a stateful object that can return the next value in the next() container when you invoke the method, any object that implements the __iter__ and __next__() method is an iterator, __iter__ returns the iterator itself, __next__ returns the next value in the container, and if there are no more elements in the container, It is not important to throw stopiteration exceptions, as to how they are implemented.

  iterators are a way to access elements within a collection. The iterator object is accessed from the first element of the collection until all the elements have been accessed one after the other .

  (1) Four characteristics of iterators

    1. Fall generation Set, string, ordered sequentially---------that there can be iterated objects

2. Thread insecure, multi-threaded access to the same set modification error.

3. For data structures that cannot be accessed randomly, iterators are the only option

4. Iterate over the current element only, not before or after the iteration(2) Use of iterators    LST = range (2)it = iter (LST)print (IT)

Output: <listiterator object at 0x00bb62f0>

Print (It.next ()) #输出: 0

Print (Next (IT)) #输出: 1

  (3) An iterator object is automatically generated in the back of Python

For IDX, ele in Enumerate (LST):

Print idx, ele

Second, Generator

The builder is actually a special iterator, but it's more elegant. It doesn't need to be written and done like the class above __iter__() __next__() , just a yiled keyword. The generator must be an iterator (and vice versa), so any generator also generates values in a lazy-loaded pattern.

Characteristics:

1. Derivation + (x+1 for x in lst) = Generator expression, return iterator, outer brackets can be omitted when used for parameters

2. Or yield: generated and generated only once, and stopped to this

(1) Base Code of the generator

     Def get_0_1_2 ():

Yield 0

Yield 1

Yield 2

Print (get_0_1_2)

Output: <function get_0_1_2 at 0x00b2cb70>

(2) the Call builder function returns a generator:

      Generator = Get_0_1_2 ()

Print (Generato)

Output: <generator object get_0_1_2 at 0x00b1c7d8>

Print (Generator.next ()) output: 0

Print (Generator.next ()) Output: 1

Print (Generator.next ()) Output: 2

Three, closed package

Definition: Closures are entities that are composed of functions and their associated reference environments (i.e. closures = functions + reference environments)

Closures are interpreted as: if, in an intrinsic function, a reference is made to a variable in an outer scope (but not at the global scope), the intrinsic function is considered a closure.

#含有内部函数--closures

def funx (x):
Print ("Start")
def funy (y):
Print ("calculation")
Return X*y
Return Funy
A=funx (3) #返回的时内部函数FunY
B=a (5)
Print (b)

Output: 15

Funy is defined in the code block of the Funx function. We call Funy the intrinsic function of funx.

Variables defined in the FUNX local scope can be accessed directly in the local scope of the Funy.
Simply put, this intrinsic function can use the behavior of an external function variable, called a closure.

Four, decorative device

Python treats everything as a subclass of Objec T, meaning that everything is an object, so functions can be directed and passed like variables.

Def Diguo ():
Print ("Pan 50")
Return 50
def doupi (FN):
Def Jia ():
Print ("Bean curd 10")
RETURN fn () +10
Return Jia
Def Xiang (FNN):
Def Jia ():
Print ("coriander")
Return FNN () +5
Return Jia
Aa=doupi (Xiang (Diguo))
Print (AA ())

The next blog will explain the closures and decorators in detail.

Iterators and generators in Python, as well as decorations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.