0

I am following this: Build a Basic Python Iterator

I have a version of this code, written as a generator function, that works.

Now I want to convert the generator function to a class.

This is what I have:

class Frange(object):
    def __init__(self, value, end=None, step=1.0):

        if end is None:
            self.start, self.end = 0.0, value
            self.step = step
        else:
            self.start = value
            self.end = end
            self.step = step

    def __iter__(self):
        return self

    def __next__(self):
        if self.start < self.end:
            return self.start

for n in Frange(0.5, 2.5, 0.5):
    print(n)

No matter what I try, I can't figure out where\how to implement the step. I either get an infinite stream of objects or 0.5.

I can see in PythonTutor that the init portion is working correctly.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
MarkS
  • 1,455
  • 2
  • 21
  • 36
  • 1
    You should have an attribute that tracks where in the iteration the current step is at. Then in `__next__` you do the arithmetic and then return the appropriate value. Remember to raise `StopIteration` when you run out of values. – Patrick Haugh Jul 10 '18 at 16:57
  • 2
    `frange` is a bad idea in the first place, the results near the endpoint can not be made reliable due to floating point limitations. – wim Jul 10 '18 at 16:58
  • Which method returns the __next__ value? Obviously, that's where you should implement that. – ForceBru Jul 10 '18 at 16:58
  • 1
    @tgikal the built-in `range` only works with integers. However, `numpy.arange` does work with floats. – DeepSpace Jul 10 '18 at 17:10
  • 1
    Why do you expect to get anything other than the start value if `__next__` always `return self.start`, and `self.start` is never modified? – DeepSpace Jul 10 '18 at 17:12
  • I realize that what I posted does not work. All of my other attempts have failed, so I posted where I 'am', but not where I need to be. – MarkS Jul 10 '18 at 17:13
  • @DeepSpace I usually just make the floats integers with a multiplier and put them back to floats after the incrementing, I guess it may not be the best way. – tgikal Jul 10 '18 at 17:14
  • Using @Patrick Haugh's above comment, I finally got it figured out. – MarkS Jul 10 '18 at 18:22
  • Also see https://stackoverflow.com/questions/30230179/using-an-iterator-in-python – PM 2Ring Jul 11 '18 at 16:33

0 Answers0