天天看點

python iterator generator yield

個人了解,歡迎指正

1、iterator

container.__iter__() Return an iterator object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.  The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:  

iterator.__iter__() Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API. 

 iterator.next() Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.

一共三個方法:

container.__iter__():可以對容器對象調用。比如Iter=[1,2,3].__iter__(),于是生成了一個iterator對象,這個語句等價于Iter=iter([1,2,3])

iterator.__iter__():同上,對疊代器對象生成一個疊代器對象,但是會繼承原來疊代器的狀态

iterator.next():疊代器的next()方法,順序通路iter的元素。#注意疊代器隻有這個三個attribute,沒有切片屬性,不能進行切片,print Iter[1]  --》TypeError: 'listiterator' object has no attribute '__getitem__'

#encoding:utf8
Iter = iter([1, 2, 3, 4])  # <=>Iter=[1,2,3,4].__iter__()
nIter = iter(Iter)  # <=>nIter=Iter.__iter__()
print Iter.next()
print nIter.next()#繼承了Iter的狀态
for i in Iter:
    print i
#print Iter.next() --> StopIteration

'''
1
2
3
4
'''      
2、generator      
generator.next()¶ Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a next() method, the current yield expression always evaluates to None. The execution then continues to the next yield expression, where the generator is suspended again, and the value of the expression_list is returned to next()‘s caller. If the generator exits without yielding another value, a StopIteration exception is raised.        
generator.send(value) Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receive the value.        
generator.throw(type[, value[, traceback]]) Raises an exception of type type at the point where generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a StopIteration exception is raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.        
generator.close() Raises a GeneratorExit at the point where the generator function was paused. If the generator function then raises StopIteration (by exiting normally, or due to already being closed) or GeneratorExit (by not catching the exception), close returns to its caller. If the generator yields a value, a RuntimeError is raised. If the generator raises any other exception, it is propagated to the caller. close() does nothing if the generator has already exited due to an exception or normal exit.
      
generator是由yield産生的,每次yield産生一個generator的元素      
def gen(n):
    for i in range(n):
        yield i
a=gen(5)
print a.next()#0      
generator.send(value)是在當期那位置插入值      
比如a.send(6)這時a中元素為0 6 1 2 3 4      
generator.throw(type[, value[, traceback]]) Raises an exception of type type,跟raise用法差不多      
a.throw(StopIteration,'stop',)      
generator.close() :      
def gen(n):
    for i in range(n):
        yield i
a=gen(2)
print a.next()
a.close()
print a.next()#StopIteration