Python iterator
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.
Iterators cannot be rolled back and can only be iterated forward. This is not a big drawback because there is little need for a fallback in the middle of an iteration.
The common iterative methods are
The. Next () method
For: In.. Method
The common understanding of iterators is to iterate over all the elements in a collection.
Python Builder
Let's start with the simple use, and then say that you create the generator
Range: Generate a list
Range (1,5)
The result is: [1,2,3,4]
Xrange: Generating an Xrange object
Xrange (5)
The result is: xrange (5)
List (xrange (1,5))
The result is: [1,2,3,4]
List (xrange (1,5,2))
The result is: [1,3]
Range differs from xrange in that range or directly generates the entire sequence, while the xrange is gradually returned and returned at iteration. When the number of iterations is too large, or if there is an interruption, using xrange can reduce memory usage and increase efficiency.
The function that contains yield in Python is a generator (very likely)
Yield is actually the same as return, except that a generator is returned
Define a generator
def nub ():
NUB = range (1,5)
For I in NUB:
Yield I*i
The type () can be used to see the nub of the function, and the function will run when the iteration (which can use Next ()), and the function will remain in the last run after each run, with an error when the iteration ends.
Python decorator
The adorner is a well-known design pattern, which is often used in scenes where there is a demand for facets, with the classic insert log, performance test, transaction processing, and so on. Decorators are a great design for solving such problems, and with adorners, we can pull out a lot of the same code that is not relevant to the function itself and continue to reuse it. In summary, the function of an adorner is to add additional functionality to an already existing object.
Pick up someone else's code.
#-*-coding:utf-8-*-import Time def foo (): print ' in foo () ' # defines a timer, passes in one, and returns another method with the timer function added Def timeit (func): # fixed An inline wrapper function that adds a timer function to the incoming function. def wrapper (): start = Time.clock () func () end =time.clock () print ' Used: ', End-start # Returns the Wrapped function to return wrapper foo = Timeit (foo) foo ()
function foo is decorated with function Timeit
Python builder, iterator, adorner