Iterator (iterator) protocol
· In Python, the support iterator protocol is the __iter__ () and __next__ () methods that implement the object.
1. __iter__ () Method: Returns the Iterator object itself;
2. __next__ () Method: Returns the next element in the container and throws an stoplteration abort iterator at the end.
an Iterative object (iterable)
· An object that implements an iterator protocol is an iterative object.
· How to implement an iterator protocol: an __iter__ () method is defined within an object.
· In Python, the string, tuple, list, dict, set, and file are all iterative objects. In short, you can call out the __iter__ () method with the Python built-in function, which is an iterative object.
As follows:
- # str1= ' Hello '
- # list1=[1,2,3]
- # tup1= (a)
- # dic={' x ': 1}
- # s1={' A ', ' B ', ' C '}
- # f=open (' A.txt ', ' W ', encoding= ' utf-8 ')
Can be debugged with __iter__ ().
Iterator Object
· Iterator object:
Refers to objects that have both built-in __iter__ methods and built-in __next__ methods. Only files are iterator objects
As follows:
- # f=open (' db.txt ', ' RT ', encoding= ' utf-8 ')
- # Print (f.__next__ ())
- # Print (f.__next__ ())
- # print (Next (f))
Disadvantages of Iterators
1. The value of the iterator is not as flexible as the index, because it can only be taken back.
2. Cannot predict the number of iterator values
As follows:
- name=[' Egon ', ' alex_sb ', ' WXX_SB ']
- RES=NAME.__ITER__ ()
- Print (res.__next__ ())
- Print (Name[0])
Iterator benefits
- For data structures that support random access: list, tuple, and so on, the iterator has no advantage over the classic for loop (indexed access), but loses the index value. However, you can use the built-in function to
enumerate() retrieve this index value. But for data structures that cannot be accessed randomly: set() iterators are the only way to access elements.
- Save Memory: iterators do not need to prepare all the elements of the entire iteration in advance, only the element is evaluated when iterating to an element, and the element may not exist or be destroyed before or after that. This is also one of the great advantages of iterators: It is suitable for traversing a large or infinite set, such as a file of several G. Let's take the Fibonacci sequence as an example:
- The code, which is printed directly in
fab(max) print, causes the reusability of the function to become worse, so Fab returns none. Other functions cannot get the sequence returned by the FAB function;
- Code two satisfies the requirement of reusability, but occupies the memory space;
- Code three Fabs class through
next()Continuously returns the next number of columns, and memory consumption is always constant.#代码一:DefHa(max): L = [] n, a, B =0,0,1While n < Max:l.append (b) A, B = B, A + b N = n +1Return L#代码二:DefFab(max): N, a, B =0,0,1While n < max:Print B A, B = B, A + b N = n +1#代码三:Classfab (object): def __init__ (self, max): Self.max = Max SELF.N, self.a, self.b = Span class= "Hljs-number" >0, 0, 1 < Span class= "Hljs-keyword" >def __iter__ (self): return self def Nextif self.n < Self.max:r = Self.b self.a, self.b = sel f.b, SELF.A + self.b SELF.N = SELF.N + 1 return R raise stopiteration ()
Iterators in Python