How do I call the function next() without type it again?

Question:

The idea is to be able to call the next number every time it is called data, but as you know I cant type next() everytime in the code, is there a way to achieve that? thanks for your help.

class Sample():
    def __init__(self, begin, end):
        self.begin = begin
        self.end = end
        #self.counter = 0
    
    def number(self):
        for i in range(self.begin, self.end):
            #self.counter +=1
            yield i
            

instance = Sample(begin=525, end=535)
data = instance.number()

print(next(data))
print(next(data)) 
print(next(data)) 

I cant use loops this time becuse I want to get one number one by one everytime it called data, example call data: 526. calls data 527. calls data 527 like this. not 526,527,528,529…… thanks

Asked By: wally

||

Answers:

You can hide the call to next() in a property getter.

class Sample():
    def __init__(self, begin, end):
        self.begin = begin
        self.end = end
        self._sequence = self.number()

    def number(self):
        for i in range(self.begin, self.end):
            yield i

    @property
    def counter(self):
        return next(self._sequence)

instance = Sample(begin=525, end=535)

print(instance.counter) # prints 525
print(instance.counter) # prints 526

However, if you use it this way, you’ll need your own handler for the StopIteration exception that’s raised when you reach the end of the iterator.

Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.