subclass list
Mark McEahern
mark at mceahern.com
Mon Feb 11 16:53:40 EST 2002
Suppose I want to subclass list so that my subclass has optionally unique
values. I'm using Python 2.2, so I start out like this:
class Bucket(list):
def __init__(self, unique):
self.unique = unique
# Use a dict to keep track of unique values.
if self.unique:
self.keys = {}
Q: How do I override append() so that I can determine whether to add the
value or not?
I tried:
def append(self, value):
if not self.unique or (self.unique and not
self.keys.has_key(value)):
list.append(value)
if self.unique:
self.keys[value] = None
But then I get:
Traceback (most recent call last):
File "./junk.py", line 31, in ?
print getRandom(count=10)
File "./junk.py", line 29, in getRandom
bucket.append(random.randint(low, hi))
File "./junk.py", line 22, in append
list.append(value)
TypeError: descriptor 'append' requires a 'list' object but received a 'int'
Thanks,
// mark
More information about the Python-list
mailing list