I would like to make a class with a method that returns incrementing numbers, starting with 0.
The most straightforward way to do it, I think, is this:
class NumbersFromZero:
def __init__(self):
self.c = 0
def get_number(self):
n = self.c
self.c += 1
return n
It’s just 8 lines, which is good, but it has an obvious disadvantage of having to create another variable, as we can’t do anything after return.
Of course, we can do some tricks such as starting with -1
, or just incrementing the number and returning it with subtraction, but it certainly feels less Pythonic, and, for most programs, is just not worth it.
So another solution I can think of is using a generator function:
class NumbersFromZero:
def __init__(self):
self.c = 0
self.generator_object = self.numbers_generator()
def numbers_generator(self):
while True:
yield self.c
self.c += 1
def get_number(self):
return next(self.generator_object)
Though it is 12 lines of code, feels nice, i.e. everything is simple to read.
But is there a more Pythonic, and perhaps easy, way to do it?