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实用编程技巧进阶

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值