Help me override append function of list object

Peter Otten __peter__ at web.de
Tue Jan 30 10:47:23 EST 2007


jeremito wrote:

> I have created a class that inherits from the list object.  I want to
> override the append function to allow my class to append several
> copies at the same time with one function call.  I want to do
> something like:
> 
> import copy
> 
> class MyList(list):
>   __init__(self):
>     pass
> 
>   def append(self, object, n=1):
>     for i in xrange(n):
>         self.append(copy.copy(object))
> 
> Now I know this doesn't work because I overwrite append, but want the
> original functionality of the list object.  Can someone help me?

Use list.append(self, obj) or super(MyList, self).append(obj), e. g.:

>>> import copy
>>> class List(list):
...     def append(self, obj, n=1):
...             for i in xrange(n):
...                     super(List, self).append(copy.copy(obj))
...
>>> items = List()
>>> items.append(42, 3)
>>> items
[42, 42, 42]

Peter



More information about the Python-list mailing list