how would you sort a class object? have a card class, and in the card class, you can have the suits and face value of a card.

how would you sort the cards by face values? (smallest to biggest?)


This is very unclear, you got to give us some code!


ok well, i've got another example, and it deals with a movie class.

how the movie class works is that it stores the name, year and genre of a movie.

m1 = Movie("Wanted", 2008, Action)
m1.year = 2008
m1.title = "Wanted"
m1.genre = Action

i also have a file with various movies in the text.

my task: read the file and sort all the movies according to year, title, and genre.

here's my code so far:

from movie import *

def findLast(line,char):
    for i in range(len(line)-1, -1, -1):
        if line[i] == char:
            return i
    return -1

m1 = []
file1 = open("movies.txt", "r")
for line in file1:
    tab = line.find("\t")
    newLine = line.find("\n")
    tab2 = findLast(line,"\t")
    title = line[:tab]
    year =line[tab+1:tab2]
    genre = line[tab2+1:newLine]

as you can see, i've taken the entire file and shoved it into a list.

is there a way i can sort the list according to title, year and genre? or am i doing this completely wrong?

ah... that certainly works.... you have a way to sort it without using the operator module?

i'm not really sure how to use it.

By adding a __cmp__ method to class Movie, you can sort instance objects in list m1 with list method sort(). Following is an example of a __cmp__ overload in a Vector class that sorts on the x, y and z attributes:

def __cmp__(self, other, epsilon=0.000001):
        x = abs(self.x-other.x)
        if x < epsilon:
            y = abs(self.y-other.y)
            if y < epsilon:
                return cmp(self.z, other.z)
            return cmp(self.y, other.y)
        return cmp(self.x, other.x)

You can also define your own comparison function and pass it to list method sort(). Example using Point objects:

pts = [p1,p2,p3,p4]
>>> pts
[Point(5.000000, 5.000000, 5.000000), Point(7.000000, 10.000000, 6.000000), Point(1.000000, 15.000000, 7.000000), Point(20.000000, 20.000000, 20.000000)]
>>> def comp(a, b):
... 	if a.x == b.x:
... 		if a.y == b.y:
... 			return cmp(a.z, b.z)
... 		return cmp(a.y, b.y)
... 	return cmp(a.x, b.x)
>>> pts.sort(comp)
>>> pts
[Point(1.000000, 15.000000, 7.000000), Point(5.000000, 5.000000, 5.000000), Point(7.000000, 10.000000, 6.000000), Point(20.000000, 20.000000, 20.000000)]

ahaha yeah. thanks solsteel. that really helped!