Understanding __call__ and list.sort (key)

I have the following code that 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 I understand it, __call__this is what is called when called object()- the call of the object as a function.

I do not understand how nums.sort(key=DistanceFrom(10)). How it works? Can someone explain this line?

Thank!

+5
source share
5 answers

Here I have defined a function DistanceFrom()that can be used similarly to your class, but it may be easier to follow

>>> def DistanceFrom(origin):
...     def f(x):
...         retval = abs(x - origin)
...         print "f(%s) = %s"%(x, retval)
...         return retval
...     return f
... 
>>> nums = [1, 37, 42, 101, 13, 9, -20]
>>> nums.sort(key=DistanceFrom(10))
f(1) = 9
f(37) = 27
f(42) = 32
f(101) = 91
f(13) = 3
f(9) = 1
f(-20) = 30
>>> nums
[9, 13, 1, 37, -20, 42, 101]

, , , DistanceFrom, nums, nums

+7

__call__ python , . :

>>> dis = DistanceFrom(10)
>>> print dis(10), dis(5), dis(0)
0 5 10
>>> 

. 10, .

+8

nums key DistanceFrom(10). , key . "" 10, 9 10, 101 .

key sort, ( x), x .

+4

-, , , . , __call__, , .

:

class DistanceFrom(object):
        def __init__(self, origin):
            self.origin = origin
        def __call__(self, x):
            return abs(x - self.origin) 

:

def distance_from(origin, other):
    return abs(other - origin)

key , Python:

, : key=str.lower. None ( )

+1

Python , , . Google.

key - , . googling sort site:http://docs.python.org/, key=.

__call__ - , , , . googling __call__ site:http://docs.python.org/, __call__.

+1

All Articles