Discussion:
Help me override append function of list object
jeremito
2007-01-30 15:35:17 UTC
Permalink
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?

Thanks,
Jeremy
Peter Otten
2007-01-30 15:47:23 UTC
Permalink
Post by jeremito
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
import copy
pass
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?
Post by jeremito
import copy
... def append(self, obj, n=1):
... for i in xrange(n):
... super(List, self).append(copy.copy(obj))
...
Post by jeremito
Post by jeremito
items = List()
items.append(42, 3)
items
[42, 42, 42]

Peter
jeremito
2007-01-30 15:55:30 UTC
Permalink
Post by Peter Otten
Post by jeremito
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
import copy
pass
self.append(copy.copy(object))
Now I know this doesn't work because I overwrite append, but want the
Post by jeremito
import copy
... super(List, self).append(copy.copy(obj))
...>>> items = List()
Post by jeremito
Post by jeremito
items.append(42, 3)
items[42, 42, 42]
Peter
Thank you so much. I'm glad it is so easy.
Jeremy

Loading...