从 Python3 的官方文档可知,Python3中的切片的魔术方法不再是Python2中的__getslice__(), __setslice__()和__delslice__(),而是借助 slice 类整合到了__getitem__(),__setitem__()和 __delitem__()中。
具体如下:
-
__getslice__(),__setslice__()and__delslice__()were killed. The syntaxa[i:j]now translates toa.__getitem__(slice(i, j))(or__setitem__()or__delitem__(), when used as an assignment or deletion target, respectively).
Python2 中的切片魔术方法
Python2 中切片魔术方法的使用示例如下:
#-*- coding:utf-8 -*-
#File Name:slice_operator_python2.py
#Created Time:2018-12-31 18:15:56
class Foo(object):
def __getslice__(self, i, j):
print('__getslice__', i, j)
def __setslice__(self, i, j, sequence):
print('__setslice__', i, j)
def __delslice__(self, i, j):
print('__delslice__', i, j)
if __name__ == "__main__":
obj = Foo()
obj[-1:1] # 自动触发执行 __getslice__
obj[0:1] = [11,22,33,44] # 自动触发执行 __setslice__
del obj[0:2]
运行结果如下:

python2 中运行结果
如果换用Python3,则会提示如下错误:

Python3运行结果
Python3 中的切片魔术方法
#-*- coding:utf-8 -*-
#File Name:slice_operator.py
#Created Time:2018-12-31 17:50:31
class Foo(object):
def __getitem__(self, index):
if isinstance(index, slice):
print("Get slice---------> start: %s, stop: %s, step: %s." \
% (str(index.start), str(index.stop), str(index.step)))
def __setitem__(self, index, value):
if isinstance(index, slice):
print("Set slice---------> start: %s, stop: %s, step: %s." \
% (str(index.start), str(index.stop), str(index.step)))
print("\tThe value is:", value)
def __delitem__(self, index):
if isinstance(index, slice):
print("Delete slice------> start: %s, stop: %s, step: %s." \
% (str(index.start), str(index.stop), str(index.step)))
if __name__ == "__main__":
obj = Foo()
obj[-1:10]
obj[-1:10:1] = [2,3,4,5]
del obj[-1:10:2]
python3 中的运行结果:

Python3中运行结果