Pyhton中序列类型支持切片功能,比如list:
>>> numbers = [1, 2, 3, 4, 5]>>> numbers[1:3]
[2, 3]
tuple也是序列类型,同样支持切片。
(一)我们是否可以使自定义类型支持切片呢?
在Python中创建功能完善的序列类型不需要使用继承,只要实现符合序列协议的方法就可以,Python的序列协议需要__len__, __getitem__两个方法,比如如下的Vector类:
from array importarrayclassVector:
type_code= 'd'
def __init__(self, compoments):
self.__components =array(self.type_code, compoments)def __len__(self):return len(self.__components)def __getitem__(self, index):return self.__components[index]
我们在控制台查看下切片功能:
>>> v1 = Vector([1, 2, 3])>>> v1[1]2.0
>>> v1[1:2]
array('d', [2.0])
在这里我们将序列协议委托给self.__compoments(array的实例),只需要实现__len__和__getitem__,就可以支持切片功能了。
(二)那么Python的切片工作原理又是怎样的呢?
我们通过一个简单的例子来查
最后
以上就是顺心冰棍最近收集整理的关于fluent python 2nd edition_Fluent Python: Slice的全部内容,更多相关fluent内容请搜索靠谱客的其他文章。
发表评论 取消回复