I have a questions about python sorting functions. I cannot digest how it works actually. Here is my class:
class DataScript(object):
def __init__(self, index, name, size):
self.index = index
self.name = name
self.size = size
def __cmp__(self, other):
if hasattr(other, 'getKey'):
if self.getKey() == other.getKey():
return 0
else:
if self.getKey() > other.getKey():
return 1
else:
return -1
def getKey(self):
return self.size
def __iter__(self):
return self
def __next__(self):
self.index += 1
try:
return data[self.index - 1]
except IndexError:
self.idx = 0
raise StopIteration # Done iterating.
def __repr__(self):
return '[' + str(data.index) + ', ' + data.name + ', ' + convert_bytes(data.size) + ']'
It is said that I have to give the list which I want to sort and the getKet function to get the sorting key. However when I try to run such a thing like this: I get an error that something is not iterable or there is no getKey function for the object in question ? Here is how I call it and I have to say it has no sense for me. First example doesn't work and I'm guessing it cannot actually determine item index and doing nothing. Second example works and I don't understand why.
sorted(resultList, key=resultList.getKey)
or
resultList.sort(key=resultList.getKey)