1. 程式人生 > >python用類實現xrange

python用類實現xrange

class xrange(object):
    def __init__(self, start, end=0, step=1):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        if self.end == 0:
            self.end = self.start
            self.start = 0
        while self.start < self.end and self.step > 0:
            yield self.start
            self.start += self.step
        while self.start > self.end and self.step < 0:
            yield self.start
            self.start += self.step