python学习笔记(28)--通过字符串访问方法

来源:互联网 发布:网络上流行的算术题 编辑:程序博客网 时间:2024/05/19 12:29

我们想调用对象上的某一个方法,这个方法名保存在字符串中,我们想通过这个字符串来调用该方法。

1 使用getattr()

import mathclass 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)

通过getattr()就可以寻找到相关方法并返回该方法,直接用就可以

2 使用operator.methodcaller()

import operatord = operator.methodcaller('distance', 0, 0)(p)print(d)

同样也达到了我们想要的结果。

如果想通过名称来查询方法并提供同样的参数反复调用该方法,那么operator.methodcaller()是很有用的。

points = [Point(12,5),Point(3,4),Point(6,9)]print(points)points.sort(key=operator.methodcaller('distance',0,0))print(points)

调用一个方法实际上涉及到两个单独的步骤,一个时查询属性,一个时函数调用,因此要调用一个方法,可以使用getattr()来查询相应的方法,只要把查询到的方法当做函数使用就好。
与getattr()不同的是,operator.methodcaller()创建了一个可以调用的方法,我们需要为其提供相应的self参数,也就是相应的对象的实例就可以直接使用。

通过包含在字符串中的名称来调用方法,这种方式常出现在需要模拟case语句或者访问者模式的变体中,以后在分享更加高级的访问者模式。

0 0
原创粉丝点击