How to implement __delitem__ to handle all possible slice scenarios?

时光怂恿深爱的人放手 提交于 2019-12-01 21:34:49

问题


I work on a class with and embedded list.

class a:
    def __init__(self, n):
        self.l = [1] * n
    def __getitem__(self, i):
        return self.l[i]
    def __delitem__(self, i):
        print type(i)
        print i

I want to use the del operator with the full syntax of slices:

p = a(10)
del p[1:5:2]

The __delitem__ receives a slice object if the parameter is not a single index. How can I use the slice object to iterate through the specified elements?


回答1:


The indices method of the slice object will, given the length of the sequence, provide the canonical interpretation of the slice that you can feed to xrange:

def __delitem__(self, item):
    if isinstance(item, slice):
        for i in xrange(*item.indices(len(self.l))):
            print i
    else:
        print operator.index(item)

The use of slice.indices makes sure that you get correct behavior in cases pointed out by Dunes. Also note that you can pass the slice object to list.__delitem__, so if you only need to do some preprocessing and delegate actual deletion to the underlying list, a "naive" del self.l[i] will in fact work correctly.

operator.index will make sure that you get an early exception if your __delitem__ receives a non-slice object that cannot be converted to an index.




回答2:


slice objects have start, stop, and step attributes that you can use to get each of those components. For example:

def __delitem__(self, i):
    if isinstance(i, slice):
        for j in xrange(i.start, i.stop, i.step):
            print j
    else:
        print i


来源:https://stackoverflow.com/questions/12986410/how-to-implement-delitem-to-handle-all-possible-slice-scenarios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!