My question is will the init method of list class calling other method such as append or insert to achieve its functionality.
like:
class test(list):
def __init__(self,values):
super().__init__()
def append(self, value):
self.append(value + 1)
I want:
x = test([1,2,3])
x
[2,3,4]
but I got:
[1,2,3]
I know I can make it work by overload init itself.
def __init__(self,values):
super().__init__([x+1 for x in values])
Can I just overload some basic value insert method like setitem, so all the insert operation like append, insert will call it, and therefore have that addition effect.
thanks for any suggestion.
解决方案
I've seen another example overriding form collections.MutableSequencethat would let you get this functionality. I'm not sure if this is more convenient than your initial idea, but it will increment any numbers during __init__, append, insert, and extend
class IncList(collections.MutableSequence):
def __init__(self, int_list):
self._list = []
for el in int_list:
self.append(el)
def __len__(self): return len(self._list)
def __getitem__(self, item): return self._list[item]
def __delitem__(self, item): del self._list[item]
def __setitem__(self, index, value):
self._list[index] = value + 1
def insert(self, index, value):
self._list.insert(index, value + 1)
def __str__(self):
return str(self._list)
def __repr__(self):
return "%s(%r)" % (self.__class__, self._list)
> l = IncList([1, 2, 3])
> print(l)
[2, 3, 4]
> l.append(4)
> print(l)
[2, 3, 4, 5]
> l[0] = 0
> print(l)
[1, 3, 4, 5]
> l.extend([5, 6])
> print(l)
[1, 3, 4, 5, 6, 7]
> l.insert(1, 1)
> print(l)
[1, 2, 3, 4, 5, 6, 7]
See this answer for more information.