python--getitmesetitem 支持索引与分片

1、想要自己定义的python对象支持索引与分片操作就要重载__getitem__\__setitem__这两个方法。

2、__getitme__(self,index)

    这里的index参数可能类型有两种int,slice。当它是int类型时对应索引操作,当它是slice时对应分片操作。

3、__setitem__(self,index,value)

    index意义同上,value代表着要设置成的值。

例子:

#!C:InstallPython27python
#!coding:utf-8

class MyList(object):
    def __init__(self):
        self.data=[1,2,3,4,5,6,7,8]
    def __getitem__(self,index):
        if isinstance(index,slice):
            #分片操作
            return [1,2,3]
        else:
            #索引操作
            return 666

if __name__=="__main__":
    ml = MyList()
    #由于分片逻辑已经写死了,所以传一个怎样的slice对象都没事
    print ml[100:100:100]
原文地址:https://www.cnblogs.com/JiangLe/p/4959864.html