How do you implement __delitem__ when subclassing collections. MutableSequence?

Using the Alex Martelli Guide to Using Collections. MutableSequence instead of a list of subclasses () (using Python 2.6.6)

Alex suggested using

class HostList(collections.MutableSequence): """A container for manipulating lists of hosts""" def __init__(self): """Initialize the class""" self.list = list() 

I have to implement __delitem__ , or MutableSequence becomes unstable ...

 >>> import HostList as H >>> foo = H.HostList() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't instantiate abstract class HostList with abstract methods __delitem__ >>> 

I also tried to build __delitem__ with return del(ii) and return self.list.remove(ii) ... but none of them worked. How can I declare __delitem__ in this context?

EDIT: final resolution did it

  def __delitem__(self, ii): """Delete an item""" del self.list[ii] # Thank you @Thomas for the pointer about .remove() return 
+4
source share
1 answer

del ii , del(ii) : you remove the name ii from the scope of the __delitem__ function, not the list (see del )

If ii is an item in a list, you can use: self.list.remove(ii);

If ii is the index of the item in the list, you can use: self.list.remove(self.list[ii])

Update

Or, as @Thomas Wouters said, it's better to use del self.list[ii]

+5
source

Source: https://habr.com/ru/post/1347227/


All Articles