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