最简单的情况,可以使用 getattr() :
import math
class Point: def init(self, x, y): self.x = x self.y = y
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) ]
points.sort(key=operator.methodcaller('distance', 0, 0))
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有