I have the following code I am trying to understand:
>>> class DistanceFrom(object):
def __init__(self, origin):
self.origin = origin
def __call__(self, x):
return abs(x - self.origin)
>>> nums = [1, 37, 42, 101, 13, 9, -20]
>>> nums.sort(key=DistanceFrom(10))
>>> nums
[9, 13, 1, 37, -20, 42, 101]
Can anyone explain how this works? As far as I have understood, __call__
is what is called when object()
is called - calling the object as a function.
What I don't understand is how nums.sort(key=DistanceFrom(10))
. How does this work? Can anyone please explain this line?
Thanks!