我正在使用 Python 3.3。我想得到一个slice
对象并用它来制作一个新range
对象。
它是这样的:
>>> class A:
def __getitem__(self, item):
if isinstance(item, slice):
return list(range(item.start, item.stop, item.step))
>>> a = A()
>>> a[1:5:2] # works fine
[1, 3]
>>> a[1:5] # won't work :(
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
a[1:5] # won't work :(
File "<pyshell#9>", line 4, in __getitem__
return list(range(item.start, item.stop, item.step))
TypeError: 'NoneType' object cannot be interpreted as an integer
好吧,这里的问题很明显 -range
不接受None
作为值:
>>> range(1, 5, None)
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
range(1, 5, None)
TypeError: 'NoneType' object cannot be interpreted as an integer
但是(对我来说)不明显的是解决方案。我将如何调用range
,以便在每种情况下都能正常工作?我正在寻找一种很好的pythonic方式来做到这一点。