Iterators/Generators/decorators

Source: Internet
Author: User

Iterators

An iterator object requires an object that supports an iterator protocol, in Python, an iterator protocol is an implementation of an object's __iter__ () and Next () methods . where the __iter__ () method returns the Iterator object itself; the next () method returns the next element of the container and throws a Stopiteration exception at the end

Can iterate over objects

if given a list or tuple, we can traverse the list or tuple through a for loop, a traversal we call Iteration (iteration) , the default List , tuple , Stri , Dict objects can be iterated.

isinstance (object,classinfo) Method Description

if the parameter object is an instance of ClassInfo, or object is an instance of the subclass of the ClassInfo class that returns True. If object is not a given type, the returned result is always false.

How can I tell if an object is an iterative object?

>>> fromcollections Import iterable

>>>isinstance (' abc ', iterable)

True

>>>isinstance ([1,2],iterable)

True

>>>isinstance (123,iterable)

False

>>>isinstance ({' K1 ': ' v1 '},iterable)

True

List-Generated

used to create List the generated type

If you want to build [1*1,2*2,3*3,4*4.....10*10] What do you do with such a list?

Traditional practices:

List1 = []

For I in Range (1,11):

List1.append (I*i)

Print (List1)

To use the list-generated formula:

List2 = [I*i for i InRange (1,11)]

Print (LIST2)

using list generation, you can quickly generate list, you can derive another list from a list, but the code is very concise.

Generator (Generator)

If we need a list of very many elements, but we only need to access the previous few elements, if using the traditional method, once created the list will occupy a lot of storage space, at this time, we need one side to use, while generating elements of the mechanism, so do not have to create a complete list, thus saving a lot of space. In Python, this side loop computes the mechanism, called the Generator (Generator).

Creating generators

The first simple way to put the list-generated [] instead ()

>>> List2 = (i*i for i in range (1,11))

>>>print (List2,type (LIST2))

<generator object<genexpr> at 0x000001f4a35ad678> <class ' generator ' >

The second approach: using yield

If a function definition contains yield keyword, then this function is no longer a normal function, but a Generator

To generate a Fibonacci sequence:

def fib (max):

N, a, b = 0, 0, 1

While n < max:

# print (b)

Yield b

A, B = B, A + b

n = n + 1

Return ' Done '

A = FIB (20)

Print (Next (a))

Print (Next (a))

Use yield after that, the execution flow of the generator:

functions are executed sequentially, encountered return statement or the last line of the function statement is returned. the function that becomes generator is executed every time the next () is called, the yield statement is returned, and the last returned continue execution at yield statement

Generator is a very powerful tool, in Python, you can simply change the list generation to generator, or you can implement the generator of complex logic through functions.

To understand how generator works, it is continuously calculating the next element during the for loop and ending the For loop in the appropriate condition. For the generator of a function, a return statement or execution to the last line of the function body is the end of the generator instruction, and the For loop ends with it.

What is the difference between a generator and a normal function call returning a result?

Normal function call returns the result directly

the generator call actually returns a Generator Object

Decorative Device

Add new functionality to the functionality that has been implemented, in a way that dynamically adds functionality without changing the way the source has been called, called an adorner (Decorator)

#!/usr/bin/envpython

#-*-coding:utf-8-*-

# simple implementation of adorners

# original version, without validation

def Web ():

Print (' WebData. ' ) )

Web ()

# version one, with authentication

# problem: Authpass occurs when I do not execute the Web () and only perform assignments. Apparently not.

def Auth (func):

Print (' Authpass. ' ) )

return func

def Web ():

Print (' WebData. ' ) )

Web=auth (web)

Web ()

# version two, to be verified, and to resolve the above call problem, use @ to invoke the adorner

def Auth (func):

def inner ():

Print (' Authpass. ' ) )

Func ()

return Inner

@ Auth

def Web ():

Print (' WebData. ' ) )

Web ()

This article is from the "Small New study Blog" blog, please be sure to keep this source http://oneserver.blog.51cto.com/4776118/1771396

Iterators/Generators/decorators

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.