Python魔法方法-__getslice__,__setslice__,__delslice__

__getslice__,__setslice__,__delslice__

该三个方法用于切片操作,如:列表(仅2.x版本)

# -*- coding:utf_8 -*-
class Foo(object):
    def __getslice__(self, i, j):
        print('__getslice__', i, j)

    def __setslice__(self, i, j, sequence):
        print('__setslice__', i, j,sequence)

    def __delslice__(self, i, j):
        print('__delslice__', i, j)


obj = Foo()
# 自动触发执行__getslice__
obj[-1:1]
# 自动触发执行__setslice__
obj[0:1] = [11, 22, 33, 44]
# 自动触发执行__delslice__
del obj[0:2]

从 Python3 的官方文档可知,Python3中的切片的魔术方法不再是Python2中的getslice(), setslice()和delslice(),而是借助 slice 类整合到了getitem(),setitem()和 delitem()中。

class Foo(object):
    def __getitem__(self, index):
        if isinstance(index, slice):
            print("getitem> 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("setitem> start: %s, stop: %s, step: %s." % (str(index.start), str(index.stop), str(index.step)))
            print("The value is:", value)

    def __delitem__(self, index):
        if isinstance(index, slice):
            print("delitem> 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]
"""
输出如下:
getitem> start: -1, stop: 10, step: None.
setitem> start: -1, stop: 10, step: 1.
The value is: [2, 3, 4, 5]
delitem> start: -1, stop: 10, step: 2.
"""

你可能感兴趣的:(Python魔法方法-__getslice__,__setslice__,__delslice__)