Help me override append function of list object

J

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
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
 
P

Peter Otten

jeremito said:
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.:
.... def append(self, obj, n=1):
.... for i in xrange(n):
.... super(List, self).append(copy.copy(obj))
....[42, 42, 42]

Peter
 
J

jeremito

jeremito said:
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.:
... 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top