Customizing sequence types

Arnaud Delobelle arnodel at googlemail.com
Sun Nov 16 13:15:22 EST 2008


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.

> What does Python use to sort elements? I mean, there is a __sort__
> method in the class list or it just uses comparison operators?

Comparison operators are always used but you can sort elements according
to a key (or you can use a compare function in 2.x).

See http://docs.python.org/library/stdtypes.html#mutable-sequence-types

> In this case, shall I just redefine this operators in the element
> classes?

Or sort them according to a key.

> 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__?

If I were you, I wouldn't inherit from list because it seems that your
list-like object quite different from a plain list.

-- 
Arnaud



More information about the Python-list mailing list