Iterators (was: Re: [Tutor] text module)
Ibraheem Umaru-Mohammed
iumarumo@eidosnet.co.uk
Sun, 1 Sep 2002 02:03:04 +0100
["Ibraheem Umaru-Mohammed"="Ibraheem"]
Ibraheem >> ,---- [ myrange.py => Iterators ]
Ibraheem >> | #!/usr/bin/env python
Ibraheem >> |
Ibraheem >> | class MyRange:
Ibraheem >> | def __init__(self,step=1):
Ibraheem >> | self.zeroToTen = ["zero", "one", "two","three","four","five","six","seven","eight","nine","ten" ]
Ibraheem >> | self.index = 0
Ibraheem >> | self.step = step
Ibraheem >> |
Ibraheem >> | def __iter__(self):
Ibraheem >> | return self
Ibraheem >> |
Ibraheem >> | def next(self):
Ibraheem >> | if self.index >= len(self.zeroToTen):
Ibraheem >> | raise StopIteration
Ibraheem >> | index = self.index
Ibraheem >> | self.index += self.step
Ibraheem >> | return self.zeroToTen[index]
Ibraheem >> |
Ibraheem >> | if __name__ == "__main__":
Ibraheem >> | myrange = MyRange(1)
Ibraheem >> | for item in myrange:
Ibraheem >> | print item
Ibraheem >> |
Ibraheem >> | myrange = MyRange(3)
Ibraheem >> | for item in myrange:
Ibraheem >> | print item
Ibraheem >> `----
Ibraheem >>
Don't know what happened there, but take care with the tabs/spaces above.
Kindest regards,
--ibz.
--
Ibraheem Umaru-Mohammed
"ibz"
umarumohammed (at) btinternet (dot) com