Reset variables within object to initialized values

Viewed 67

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())
1 Answers

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)
Related