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!
Here I have defined a function
DistanceFrom()which can be used in a similar way to your class, but might be easier to followSo you see that the object returned by
DistanceFromis called once for each item ofnumsand thennumsis returned sorted in accordance with the returned values