TOPIC

磷光与烟火逆流

一个敲代码的程序猿

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
posted @ 2021-11-09 17:39  Jacobyang  阅读(208)  评论(0编辑  收藏  举报