前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 通过字符串方式调用方法operator.methodcaller

python 通过字符串方式调用方法operator.methodcaller

作者头像
用户5760343
发布2019-12-12 18:03:23
1.4K0
发布2019-12-12 18:03:23
举报
文章被收录于专栏:sktj

最简单的情况,可以使用 getattr() :

import math

class Point: def init(self, x, y): self.x = x self.y = y

代码语言:javascript
复制
def __repr__(self):
    return 'Point({!r:},{!r:})'.format(self.x, self.y)

def distance(self, x, y):
    return math.hypot(self.x - x, self.y - y)

p = Point(2, 3) d = getattr(p, 'distance')(0, 0) # Calls p.distance(0, 0) 另外一种方法是使用 operator.methodcaller() ,例如:

import operator operator.methodcaller('distance', 0, 0)(p) 当你需要通过相同的参数多次调用某个方法时,使用 operator.methodcaller 就很方便了。 比如你需要排序一系列的点,就可以这样做:

points = [ Point(1, 2), Point(3, 0), Point(10, -3), Point(-5, -7), Point(-1, 8), Point(3, 2) ]

Sort by distance from origin (0, 0)

points.sort(key=operator.methodcaller('distance', 0, 0))

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Sort by distance from origin (0, 0)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档