I want to inherit and modify Python list class to add extra functionality - i.e. a method that removes all instances of an element:
class NewList(list):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__list__ = self
def rm_all(self, qw):
rm = [x for x in self if x != qw]
return rm
So, if I do:
l = NewList([1,2,1,3,2,1,2,1,3,1,1,2])`
print(l.rm_all(1))
Output is:
[2, 3, 2, 2, 3, 2]
However, the list remains intact (I need to call l = l.rm_all(1)
to update). Whereas, in Python lists if I use l.remove(2)
the list gets updated automatically.
How can I incorporate this kind of functionality in my new inherited class - i.e. when I type l.rm_all(1)
the list automatically updates?
I assume I need to reassign self
but I can't figure it out.
CodePudding user response:
Since it's a meta class of list
, you could try changing the values of self
with the following:
class NewList(list):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__list__ = self
def rm_all(self, qw):
self[:] = [x for x in self if x != qw]
l = NewList([1,2,1,3,2,1,2,1,3,1,1,2])
l.rm_all(1)
print(l)