Customizing sequence types
Mr.SpOOn
mr.spoon21 at gmail.com
Sun Nov 16 13:44:22 EST 2008
On Sun, Nov 16, 2008 at 7:15 PM, Arnaud Delobelle
<arnodel at googlemail.com> wrote:
> Mr.SpOOn <mr.spoon21 at gmail.com> writes:
>
>> Hi,
>> I'm trying to create a class which inherit a list to change some behavior.
>> This list should contain other instance objects and has to manage
>> these instances in a particular way.
>>
>> 1) I need to sort this elements in this list, but they must be sorted
>> using an instance variable.
>
> I don't understand what this means.
Well, inside the elements I need to order there is a variable that
stores a numeric value. I need to sort the elements using this value.
> Or sort them according to a key.
Ok, knowing what to search for I cleared my ideas. I think I just have
to choose between redefining __cmp__() or using the key argument.
>> 2) I need to have just unique elements. Maybe this is related to first
>> question (or maybe not). Again, to estabilish the uniqueness of an
>> element I have to use an instance variable. I think I have to rewrite
>> both the methods append() and __contains__(), but I'm not sure how.
>>
>> For the first one I did:
>>
>> def append(self, element):
>> if element in self:
>> pass
>> else:
>> list.append(self, element)
>>
>> It seems right to me, but I have no idea what to do with __contains__()
>
> Why do you need to redefine __contains__?
Well, to check the presence of an element according to an attribute.
> If I were you, I wouldn't inherit from list because it seems that your
> list-like object quite different from a plain list.
The most obvious choice seems to be stes. But the order is really
important. Maybe the best solution is using sets and convert them to
list when I need to access them in the correct order.
>You should probably use the `bisect` module
>(http://docs.python.org/library/bisect.html) for searching and
>inserting into the list as it takes advantage of and ensures that the
>list keeps sorted. It also means that __contains__ and some other
>operations become O(log N) rather than O(N).
This seems good too, but I'd always have to check the presence of an
element before inserting a new one and it's still not clear to me how
to do it.
Thanks everybody.
More information about the Python-list
mailing list