I am attempting to implement a priority queue in Python. I am following an example that I found online. The Skill class overrides the __cmp__ method so that the priority queue can order itself. I am getting a error when I run:
TypeError: unorderable types: Skill() < Skill()
I've found several examples online that say as long as you overload the __cmp__() method the priority queue should be good.
try:
import Queue as Q # ver. < 3.0
except ImportError:
import queue as Q
class Skill(object):
def __init__(self, priority, description):
self.priority = priority
self.description = description
print ('New Level:', description)
return
def __cmp__(self, other):
return cmp(self.priority, other.priority)
q = Q.PriorityQueue()
q.put(Skill(5, 'Proficient'))
q.put(Skill(10, 'Expert'))
q.put(Skill(1, 'Novice'))
while not q.empty():
next_level = q.get()
print ('Processing level:', next_level.description)
I'm currently running Python 3.4.1 on my computer.
__cmp__is ignored in 3.x, and was replaced by rich comparison: docs.python.org/3/reference/datamodel.html#object.__lt__. See e.g. stackoverflow.com/q/8276983/3001761Skill.__init__isn't indented, and__cmp__is shown as being outside of the class altogether. What do you mean "what kind"?! Indentation is part of Python's syntax.