纯python代码实现一个range函数
2017-04-20 本文已影响770人
极光火狐狸
源代码:
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
打印类对象信息
print(range(10), MyRange(10), sep=' ' * 10)
print(range(10, 20), MyRange(10, 20), sep=' ' * 10)
# 显示结果
range(0, 10) MyRange(0, 10)
range(10, 20) MyRange(10, 20)
打印单个分片信息
print(range(10)[4], MyRange(10)[4], sep=' ' * 10)
# 显示结果
4 4
打印一组分片信息
print(range(10)[5:8], MyRange(10)[5:8], sep=' ' * 10)
# 显示结果
range(5, 8) MyRange(5, 8)
循环迭代
for i in range(10):
print('range: ', i)
print('\n')
for i in MyRange(10):
print('MyRange: ', i)
# 显示结果
range: 0
range: 1
range: 2
range: 3
range: 4
range: 5
range: 6
range: 7
range: 8
range: 9
MyRange: 0
MyRange: 1
MyRange: 2
MyRange: 3
MyRange: 4
MyRange: 5
MyRange: 6
MyRange: 7
MyRange: 8
MyRange: 9
异常处理
s = MyRange(10)
print(s[15])
# 显示结果
Traceback (most recent call last):
File "XXXXXXXX.py", line 117, in <module>
File "XXXXXXXX.py", line 69, in __getitem__
File "XXXXXXXX.py", line 65, in is_index_error
IndexError: 分片不得大于最大值.