关于Python内置函数operator中methodcaller函数

一个例子理解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

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值