python如何通過執行個體方法名字調用方法,python執行個體
本文執行個體為大家分享了python通過執行個體方法名字調用方法的具體代碼,供大家參考,具體內容如下
案例:
某項目中,我們的代碼使用的2個不同庫中的圖形類:
Circle,Triangle
這兩個類中都有一個擷取面積的方法介面,但是介面的名字不一樣
需求:
統一這些介面,不關心具體的介面,只要我調用統一的介面,對應的面積就會計算出來
如何解決這個問題?
定義一個統一的介面函數,通過反射:getattr進行介面調用
#!/usr/bin/python3 from math import pi class Circle(object): def __init__(self, radius): self.radius = radius def getArea(self): return round(pow(self.radius, 2) * pi, 2) class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def get_area(self): return self.width * self.height # 定義統一介面def func_area(obj): # 擷取介面的字串 for get_func in ['get_area', 'getArea']: # 通過反射進行取方法 func = getattr(obj, get_func, None) if func: return func() if __name__ == '__main__': c1 = Circle(5.0) r1 = Rectangle(4.0, 5.0) # 通過map高階函數,返回一個可迭代對象 erea = map(func_area, [c1, r1]) print(list(erea))
通過標準庫operator中methodcaller方法進行調用
#!/usr/bin/python3 from math import pifrom operator import methodcaller class Circle(object): def __init__(self, radius): self.radius = radius def getArea(self): return round(pow(self.radius, 2) * pi, 2) class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def get_area(self): return self.width * self.height if __name__ == '__main__': c1 = Circle(5.0) r1 = Rectangle(4.0, 5.0) # 第一個參數是函數字串名字,後面是函數要求傳入的參數,執行括弧中傳入對象 erea_c1 = methodcaller('getArea')(c1) erea_r1 = methodcaller('get_area')(r1) print(erea_c1, erea_r1)
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。