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實用編程技巧進階


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM