Iterator
behind the scenes, the for statement calls iter ( on the container object. The function returns an iterator object that defines the method __next__ () Span style= "Background-color:;" > which accesses elements in the container one at a time. When there is no more elements, __next__ () raises a stopiteration exception which tells the for loop to terminate. You can call the __next__ () method using the next () built-in function
you can implement a for loop of a class yourself:
Class A:class It:def __init__ (s,a): S.a=as.l=len (S.A.L) +len (S.A.L2) s.i=0def __next__ (s): if S.i==s.l:raise Stopiterationa=0if S.i<len (S.A.L): a= s.a.l[s.i]else:a= S.a.l2[s.i-len (S.A.L)]s.i=s.i+1return adef __init__ (s): S.l=[1,2,4,5]s.l2=[4,3,2,0]def __iter__ (s): Return a.it (s) >>> a=a () >>> [I for I in A][1, 2, 4, 5, 4, 3, 2 , 0]
Generator
GeneratorS is a simple and powerful tool for creating iterators. They is written like regular functions but with the yield statement whenever they want to return data. Each time next () was called on it, the generator resumes where it left off (it remembers all the data values and W Hich statement was last executed).
Def Gen (a): For I in A.l:yield IFOR I in A.l2:yield i>>>for I in Gen (a):p rint (i,end= ', ') 1,2,4,5,4,3,2,0,
Generator expression
Def gen (): Return ((I,J) for I in range (+) for J in Range (9)) or: For A In ((I,J) for I in range (+) for J in Range (9)):p rint (a)
For a in (... generator exp ...) A is generated at each call next (), and for a in [... list comprehension...] is to generate a list in advance, the former is said to be more efficient
Class and instance variables
I understand that for the mutable variable, the object replicates a "pointer" to the variable of the class:
>>> class A:li=[]def Add (s,x): S.li.append (x) >>> a=a () >>> A.add (3) >>> a.li[3]> >> b=a () >>> B.add (4) >>> B.li#b.li as a reference to A.li, has been modified by A.li [3, 4]
The right approach:
>>> class A:def __init__ (s): s.li=[] #每次创建对象都生成一个对象自己的列表def Add (s,x): S.li.append (x) >>> a=a () > >> A.add (3) >>> a.li[3]>>> b=a () >>> B.add (4) >>> b.li[4]
For immutable variables, it is similar to passing by value (although there is no such concept in Python).
Note on Python