By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,915 Members | 1,350 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,915 IT Pros & Developers. It's quick & easy.

Help me override append function of list object

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a


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.