I have a question about how python treats the methods passed to sorted(). Consider the following small script:
#!/usr/bin/env python3
import random
class SortClass:
def __init__(self):
self.x = random.choice(range(10))
self.y = random.choice(range(10))
def getX(self):
return self.x
def getY(self):
return self.y
if __name__ == "__main__":
sortList = [SortClass() for i in range(10)]
sortedList = sorted(sortList, key = SortClass.getX)
for object in sortedList:
print("X:", object.getX(),"Y:",object.getY())
Which gives output similar to the following:
X: 1 Y: 5
X: 1 Y: 6
X: 1 Y: 5
X: 2 Y: 8
X: 2 Y: 1
X: 3 Y: 6
X: 4 Y: 2
X: 5 Y: 4
X: 6 Y: 2
X: 8 Y: 0
This script sorts the SortClass objects according to the value of each instance's x field. Notice, however, that the "key" argument of sorted points to SortClass.getX, not to any particular instance of SortClass. I'm a bit confused as to how python actually uses the method passed as "key". Does calling getX() like this work because the objects passed to it are of the same type as the "self" argument? Is this a safe use of the "key" argument?