Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__key__ parameter for classes in Python

I have an array of vectors and I want to sort them by length:

class Vector:

     def __init__(self, x, y):
       self.x, self.y = x, y

     def __add__(a, b):
       return Vector(a.x + b.x, a.y + b.y)

     def __str__(a):
       return str(a.x) + ' ' + str(a.y) + '\n'

     def __key__(self):
       return self.x * self.x + self.y * self.y


a = []
a.append(Vector(1,2))
a.append(Vector(1, 1))
a.sort()
print("".join(map(str,a)))

It says: "unorderable types: Vector() < Vector()" It wants me to create lt, gt.. methods. But I want to sort without using cmp. Is it possible?

like image 752
emilchess Avatar asked Aug 28 '12 11:08

emilchess


2 Answers

I would implement __lt__ and __eq__ and then use the functools.total_ordering class decorator to get the rest of the comparison methods.

If it doesn't make sense to have your vectors ordered like that, then you can always just use the key keyword to sort (or sorted for that matter):

mylist.sort(key = lambda v: v.x**2 + v.y**2)
like image 124
mgilson Avatar answered Sep 28 '22 08:09

mgilson


You have two variants here: implement __cmp__ function in Vector class or perform sorting this way:

...
a.sort(key=Vector.__key__) 
like image 32
Alexey Kachayev Avatar answered Sep 28 '22 07:09

Alexey Kachayev