python--getitme\setitem 支持索引与分片,python的item方法,1、想要自己定义的p


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

2、__getitme__(self,index)

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

3、__setitem__(self,index,value)

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

例子:

#!C:\Install\Python27\python#!coding:utf-8class 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 666if __name__=="__main__":    ml = MyList()    #由于分片逻辑已经写死了,所以传一个怎样的slice对象都没事    print ml[100:100:100]

python--getitme\setitem 支持索引与分片

相关内容

    暂无相关文章

评论关闭