#-*-coding:utf-8-*-classMyClass:"""A Simple Example Class"""I= 12345def __init__(Self, L, R): Self.data=[] SELF.L=L SELF.R=Rdeff (self):return 'Hello World'Print(MYCLASS.I)Print(MyClass.__doc__) x=myclass ()Print(X.data)Print(X.L)classBag:def __init__(self): Self.data= [] defAdd (self, x): Self.data.append (x)defAddtwice (self, x): Self.add (x) self.add (x) s='ABC'it=ITER (s)Print(Next (IT))#This form of access is clear, concise and convenient. #the use of iterators is common and uniform in Python. #in the background, the For statement calls ITER () in the container object. #This function returns an iterator object that defines the next () method .#, which accesses the elements in the container. #S=iter (BAG)classReverse:"""Iterator for looping over a sequence backwards.""" def __init__(self, data): Self.data=Data Self.index=len (data)def __iter__(self):return Selfdef __next__(self):ifSelf.index = =0:Raisestopiteration Self.index= Self.index-1returnSelf.data[self.index]rev= Reverse ('spam') K=ITER (REV)Print(Next (k))Print(Next (k))#Print (next (k))#Print (next (k))#Print (next (k)) forCharinchRev:Print(char)#Generator is a simple and powerful tool for creating iterators. #They're written like normal functions,#Use the yield statement when you need to return data. #each time next () is called,#the generator replies to its detached position (it remembers where the statement was last executed and all the data values). #The following example shows that the generator can be easily created:defreverse2 (data): forIndexinchRange (len (data)-1,-1, 1): yieldData[index] forCharinchReverse2 ('Golf'): Print(char) Q= Reverse2 ("FF") P=ITER (q)Print( Next (P)) sum (i*i forIinchRange (10))#Sum of squaresXvec = [10, 20, 30]yvec= [7, 5, 3]sum (x*y forX, yinchZip (Xvec, Yvec))#dot Product
Learn python syntax from code six (continuous update)