python类与对象-如何通过实例方法名字的字符串调用方法

如何通过实例方法名字的字符串调用方法

问题举例

在某项目中我们的代码用了三个不同库中的图形类:Circle,Triangle,Rectangle

它们都有一个获取图形面积的接口,单接口名字可能不同,我们可以实现一个统一的获取

面积的函数,使用每种方法名进行尝试,调用相应类的接口。

解决思路

方法一:使用内置函数getattr, 通过名字获取方法对象然后调用

方法二:使用标准库operator下的methodcaller函数调用

代码

from lib1 import Circle
from lib2 import Triangle
from lib3 import Rectangle
from operator import methodcaller

def get_area(shape, method_name = ['area', 'get_area', 'getArea']):
    for name in method_name:
        if hasattr(shape, name):
            return methodcaller(name)(shape)
        # f = getattr(shape, name, None)
        # if f:
        #     return f()


shape1 = Circle(1)
shape2 = Triangle(3, 4, 5)
shape3 = Rectangle(4, 6)

shape_list = [shape1, shape2, shape3]
# 获得面积列表
area_list = list(map(get_area, shape_list))
print(area_list)

参考资料:python3实用编程技巧进阶

猜你喜欢

转载自www.cnblogs.com/marton/p/10847882.html