On Thu, Dec 24, 2015 at 3:54 PM, Danny Yoo <d...@hashcollision.org> wrote:
I tried to follow your example: > > For example, here's a generator that knows how to produce an infinite > stream of numbers: > > ############## > def nums(): > n = 0 > while True: > yield n > n += 1 > ############## > > What distinguishes a generator from a regular function? The use of > "yield". A "yield" is like a return, but rather than completely > escape out of the function with the return value, this generator will > remember what it was doing at that time. Why? Because it can > *resume* itself when we try to get another value out of the generator. > > Let's try it out: > > ##################### > >>>> numStream = nums() >>>> numStream.next() > 0 But I got an exception: Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def nums(): n = 0 while True: yield n n += 1 >>> numStream = nums() >>> numStream.next() Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> numStream.next() AttributeError: 'generator' object has no attribute 'next' If I instead do this: >>> next(numStream) 0 >>> next(numStream) 1 >>> next(numStream) 2 Things work as you described. Is your example from Python 2? If yes, is this something that changed between Python 2 and 3? I have not made it to generators yet, but you have now whetted my appetite! TIA! boB _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor