1

here's a newb Python question that I'm sure is a no-brainer for the pros. I have an object OddStream that is called from the function print_from_stream to create a list of odd numbers starting from 1. It works find the first time but when calling it a second time the new list starts from the last number of the first list + 2.

What should I write to reset OddStream? BTW, this is only a portion of the code, but it's the part that matters. Thanks if you can help.

class OddStream(object):
    def __init__(self):
        self.current = 1

    def get_next(self):
        to_return = self.current
        self.current += 2  
        return to_return 


def print_from_stream(n): 
    for _ in range(n):
        print(stream.get_next())
NickNaym99
  • 35
  • 5

1 Answers1

0

I guess the stream instance of the OddStream class is being instantiated like this:

class OddStream(object):
    # ...

stream = OddStream()  # Breakpoint 1

def print_from_stream(n): 
    for _ in range(n):
        print(stream.get_next()) # Breakpoint 2
  • At breakpoint 1 stream has been instantiated and stream.current = 1
  • At breakpoint 2 stream.get_next() has been called and it has increased stream.current

So the behaviour you described should be expected.

To avoid such behaviour, add a reset() method to OddStream and call it from print_from_stream():

class OddStream(object):
    # ...

    def reset(self):
        self.current = 1

stream = OddStream()

def print_from_stream(n):
    stream.reset()
    for _ in range(n):
        print(stream.get_next())


print("First run:")
print_from_stream(10)
print("Second run:")
print_from_stream(10)
Jonathan Ciapetti
  • 1,261
  • 3
  • 11
  • 16
  • 1
    Thank you very much. Adding reset() to the class definitions and calling it from the print function solved the problem. – NickNaym99 Jul 09 '22 at 14:17
  • Update: Now that I understand the syntax, I realized I could also call stream.__init__ from within the print function. That avoids having to add a reset() definition to the OddStream class. However, reset() is more obvious and better for debugging. – NickNaym99 Jul 09 '22 at 14:47
  • You could find [this](https://stackoverflow.com/questions/13091221/reinitialize-an-object-with-self-init) useful. – Jonathan Ciapetti Jul 09 '22 at 14:49