1. 程式人生 > 其它 >Python range函式 實現

Python range函式 實現

函式形式實現

def my_range(start, end=None, step=1):
    result = []
    beg = None
    if end == None:
        beg = 0
        final = start-1
    else:
        beg = start
        if step >0:final = end-1
        else: final = end+1

    if step > 0: 
        while beg<=final: 
            yield beg
            beg +=step
    elif step < 0:
        while final<=beg:
            yield beg
            beg +=step

    else:
        raise BaseException("step not allow 0")
        
for i in my_range(-1,-1):
    print(i)

物件形式實現(你物件沒了)

class MyRange:
 
    def __init__(self, start, stop=None, step=None):
 
        # 模擬range從0開始的行為
        if stop is None:
            self.start = 0
            self.stop = start - 1
        else:
            self.start = start
            self.stop = stop - 1
 
        self.step = step
 
        # 保留原始引數
        self.origin_start = self.start
        self.origin_stop = self.stop + 1
        self.origin_step = self.step
 
    def __repr__(self):
        """
        :return: 顯示錶現
        """
        if self.origin_step:
            result = '{}({}, {}, {})'.format(
                self.__class__.__name__,
                self.origin_start,
                self.origin_stop,
                self.origin_step
            )
        else:
            result = '{}({}, {})'.format(
                self.__class__.__name__,
                self.origin_start,
                self.origin_stop
            )
        return result
 
    def __iter__(self):
        return self
 
    def __next__(self):
        """
        :return: 返回當前數字,然後在當前數字上+1
        """
        result = self.start
        if self.start <= self.stop:
            self.start += 1
        else:
            raise StopIteration
 
        return result
 
    def __getitem__(self, item):
        """
        :param item: 如果是單個數字, 那麼item的型別將會是int,
                      如果是分片那麼item將會是一個slice.
        :return: 返回分片結果
        """
 
        def is_index_error(_start):
            if _start > self.stop:
                raise IndexError('分片不得大於最大值.')
 
        if isinstance(item, int):
            result = self.origin_start + item
            is_index_error(result)
        elif isinstance(item, slice):
            start = self.origin_start + item.start
            stop = self.origin_start + item.stop
            list(map(is_index_error, MyRange(start, stop)))
            result = MyRange(start, stop)
        else:
            raise KeyError
 
        return result