468,234 Members | 1,622 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,234 developers. It's quick & easy.

Help me override append function of list object

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

Jan 30 '07 #1
2 7362
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
Jan 30 '07 #2


On Jan 30, 10:47 am, Peter Otten <__pete...@web.dewrote:
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
Thank you so much. I'm glad it is so easy.
Jeremy

Jan 30 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by JustSomeGuy | last post: by
7 posts views Thread by berkay | last post: by
2 posts views Thread by Chris Millar | last post: by
1 post views Thread by Rahul | last post: by
reply views Thread by Michalis Giannakidis | last post: by
5 posts views Thread by jrod11 | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.