Home > front end >  How do I call the function next() without type it again?
How do I call the function next() without type it again?

Time:11-19

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

CodePudding user response:

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.

  • Related