python如何通過實(shí)例方法名字調(diào)用方法
本文實(shí)例為大家分享了python通過實(shí)例方法名字調(diào)用方法的具體代碼,供大家參考,具體內(nèi)容如下
案例:
某項(xiàng)目中,我們的代碼使用的2個(gè)不同庫(kù)中的圖形類:
Circle,Triangle
這兩個(gè)類中都有一個(gè)獲取面積的方法接口,但是接口的名字不一樣
需求:
統(tǒng)一這些接口,不關(guān)心具體的接口,只要我調(diào)用統(tǒng)一的接口,對(duì)應(yīng)的面積就會(huì)計(jì)算出來
如何解決這個(gè)問題?
定義一個(gè)統(tǒng)一的接口函數(shù),通過反射: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']: # 通過反射進(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) # 通過map高階函數(shù),返回一個(gè)可迭代對(duì)象 erea = map(func_area, [c1, r1]) print(list(erea))
通過標(biāo)準(zhǔn)庫(kù)operator中methodcaller方法進(jìn)行調(diào)用
#!/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) # 第一個(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í)有所幫助,也希望大家多多支持腳本之家。
- python中的實(shí)例方法、靜態(tài)方法、類方法、類變量和實(shí)例變量淺析
- 淺談python中的實(shí)例方法、類方法和靜態(tài)方法
- 深入解析python中的實(shí)例方法、類方法和靜態(tài)方法
- python解析json實(shí)例方法
- Python類的動(dòng)態(tài)修改的實(shí)例方法
- python實(shí)現(xiàn)系統(tǒng)狀態(tài)監(jiān)測(cè)和故障轉(zhuǎn)移實(shí)例方法
- python的類方法和靜態(tài)方法
- Python探索之靜態(tài)方法和類方法的區(qū)別詳解
- Python面向?qū)ο笾o態(tài)屬性、類方法與靜態(tài)方法分析
- Python實(shí)例方法、類方法、靜態(tài)方法的區(qū)別與作用詳解
相關(guān)文章
python中實(shí)現(xiàn)php的var_dump函數(shù)功能
這篇文章主要介紹了python中實(shí)現(xiàn)php的var_dump函數(shù)功能,var_dump函數(shù)在PHP中調(diào)試時(shí)非常實(shí)用,本文介紹在Python中實(shí)現(xiàn)這個(gè)函數(shù),需要的朋友可以參考下2015-01-01python實(shí)現(xiàn)多線程及線程間通信的簡(jiǎn)單方法
這篇文章主要為大家介紹了python實(shí)現(xiàn)多線程及線程間通信的簡(jiǎn)單方法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07Python隨機(jī)函數(shù)random隨機(jī)獲取數(shù)字、字符串、列表等使用詳解
這篇文章主要介紹了Python隨機(jī)函數(shù)random使用詳解包含了Python隨機(jī)數(shù)字,Python隨機(jī)字符串,Python隨機(jī)列表等,需要的朋友可以參考下2021-04-04Python分支結(jié)構(gòu)(switch)操作簡(jiǎn)介
這篇文章主要介紹了Python分支結(jié)構(gòu)(switch)操作簡(jiǎn)介,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01