python如何通過實例方法名字調用方法
本文實例為大家分享了python通過實例方法名字調用方法的具體代碼,供大家參考,具體內容如下
案例:
某項目中,我們的代碼使用的2個不同庫中的圖形類:
Circle,Triangle
這兩個類中都有一個獲取面積的方法接口,但是接口的名字不一樣
需求:
統(tǒng)一這些接口,不關心具體的接口,只要我調用統(tǒng)一的接口,對應的面積就會計算出來
如何解決這個問題?
定義一個統(tǒng)一的接口函數,通過反射: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 # 定義統(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高階函數,返回一個可迭代對象 erea = map(func_area, [c1, r1]) print(list(erea))
通過標準庫operator中methodcaller方法進行調用
#!/usr/bin/python3 from math import pi from 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) # 第一個參數是函數字符串名字,后面是函數要求傳入的參數,執(zhí)行括號中傳入對象 erea_c1 = methodcaller('getArea')(c1) erea_r1 = methodcaller('get_area')(r1) print(erea_c1, erea_r1)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- python中的實例方法、靜態(tài)方法、類方法、類變量和實例變量淺析
- 淺談python中的實例方法、類方法和靜態(tài)方法
- 深入解析python中的實例方法、類方法和靜態(tài)方法
- python解析json實例方法
- Python類的動態(tài)修改的實例方法
- python實現(xiàn)系統(tǒng)狀態(tài)監(jiān)測和故障轉移實例方法
- python的類方法和靜態(tài)方法
- Python探索之靜態(tài)方法和類方法的區(qū)別詳解
- Python面向對象之靜態(tài)屬性、類方法與靜態(tài)方法分析
- Python實例方法、類方法、靜態(tài)方法的區(qū)別與作用詳解
相關文章
python中實現(xiàn)php的var_dump函數功能
這篇文章主要介紹了python中實現(xiàn)php的var_dump函數功能,var_dump函數在PHP中調試時非常實用,本文介紹在Python中實現(xiàn)這個函數,需要的朋友可以參考下2015-01-01Python隨機函數random隨機獲取數字、字符串、列表等使用詳解
這篇文章主要介紹了Python隨機函數random使用詳解包含了Python隨機數字,Python隨機字符串,Python隨機列表等,需要的朋友可以參考下2021-04-04