一个例子理解methodcaller函数
import math
from operator import methodcaller
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'Point({0},{1})'.format(self.x, self.y)
def distance(self, x, y):
return math.hypot(self.x - x, self.y - y)
points = [Point(x, y) for x, y in zip([3, 2, 1, 0, 0.2], [0.1, -1, 5, 3, 1, 8])]
# [Point(3,0.1), Point(2,-1), Point(1,5), Point(0,3), Point(0.2, 1)]
# 按离原点的距离排序
points.sort(key=methodcaller('distance', 0, 0))
for p in points:
print(p)
结果为:
Point(0.2,1)
Point(2,-1)
Point(0,3)
Point(3,0.1)
Point(1,5)
函数解析:
math.hypot(3,4)
获得的结果为:
5.0
可以理解为知道三角形的两边计算最长的一条边
3 * 3 + 4 * 4= 5 * 5
points= [Point(x, y) for x, y in zip([3, 2, 1, 0, 0.2], [0.1, -1, 5, 3, 1, 8])]
得到的结果为:
[Point(3,0.1), Point(2,-1), Point(1,5), Point(0,3), Point(0.2, 1)]
methodcaller(‘distance’, 0, 0)
相当于调用methodcaller方法并传入参数0,0
所以此函数就是计算(3,0.1),(2,-1),(1,5),(0,3),(0.2,1)这5个点到(0,0)之间的距离并从小到大排序,最后进行遍历就得到了上述的结果。
其他用法
import math
from operator import methodcaller
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 'Point({0},{1})'.format(self.x, self.y)
def distance(self, x, y):
return math.hypot(self.x - x, self.y - y)
p = Point(3, 4)
d = methodcaller('distance',0,0)(p)
print(d)
结果为:5.0
解析:
计算(3,4)到(0,0)的距离,
methodcaller()(实例化的对象可以进行调用)后加实例化的对象可以进行调用
参考:https://blog.csdn.net/u010339879/article/details/98304292#23_methodcaller__503