本文實例為大家分享了python通過實例方法名字調(diào)用方法的具體代碼,供大家參考,具體內(nèi)容如下
案例:
某項目中,我們的代碼使用的2個不同庫中的圖形類:
Circle,Triangle
這兩個類中都有一個獲取面積的方法接口,但是接口的名字不一樣
需求:
統(tǒng)一這些接口,不關(guān)心具體的接口,只要我調(diào)用統(tǒng)一的接口,對應(yīng)的面積就會計算出來
如何解決這個問題?
定義一個統(tǒng)一的接口函數(shù),通過反射:getattr進行接口調(diào)用
#!/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 # 定義統(tǒng)一接口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高階函數(shù),返回一個可迭代對象 erea = map(func_area, [c1, r1]) print(list(erea))
通過標(biāo)準(zhǔn)庫operator中methodcaller方法進行調(diào)用
#!/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) # 第一個參數(shù)是函數(shù)字符串名字,后面是函數(shù)要求傳入的參數(shù),執(zhí)行括號中傳入對象 erea_c1 = methodcaller('getArea')(c1) erea_r1 = methodcaller('get_area')(r1) print(erea_c1, erea_r1)以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答
圖片精選