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

Re: Customizing sequence types

P: n/a
Mr.SpOOn wrote:
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. What does Python use to sort elements? I
mean, there is a __sort__ method in the class list or it just uses
comparison operators? In this case, shall I just redefine this
operators in the element classes?
By default Python uses the built-in "cmp()" function to compare pairs of
elements during its sorts. You can use the "cmp=f" argument to sort to
replace it with your own function, but if this is a Python function the
comparison *will* be slower.

Alternatively for can provide a "key=f" argument; in this case before
beginning the sort, sort() will call the provided key function for each
element of the list your are trying to sort, and then it will compare
the generated keys instead of the list elements (using Python's built-in
"cmp()" function.
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:
list.append(self, element)

It seems right to me, but I have no idea what to do with __contains__()
Why do you need to change it? For speed?
My suggestion would be to use Python's built-in sets, converting them to
lists when you need the sorted form.

Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC

Nov 16 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.