1

in the following code

class Student(object):
   def __init__(self):
       self.vals=[9,2,4,1]

   def allstudents(self):
      self.vals.sort()
      for s in self.vals:
            yield s

jack = Student()

jack.allstudents().next() -> Of course the output is 1

jack.allstudents().next() -> Here is the problem: this line's output is still 1. Why not 2?

jack.allstudents().next() -> This line's output is still 1. Why not 4?

Could anyone give me an explanation, please?

Pynchia
  • 10,996
  • 5
  • 34
  • 43
jxpisces
  • 11
  • 1
  • Note that it would be conventional to implement the `__iter__` *"magic method"*, then you can just do e.g. `for s in jack:` – jonrsharpe Aug 15 '15 at 15:11
  • please see [this SO QA](http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python) dedicated to `yield` – Pynchia Aug 15 '15 at 15:40

1 Answers1

3

Because you are constantly calling the allstudents() method again and again. Try storing it in a variable and then calling next() on the variable assigned to it, like:

var = jack.allstudents()
var.next()
var.next()

and so on.

Nhor
  • 3,860
  • 6
  • 28
  • 41