国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python如何通過實例方法名字調(diào)用方法

2020-02-22 23:31:10
字體:
供稿:網(wǎng)友

本文實例為大家分享了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í)有所幫助,也希望大家多多支持武林站長站。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 呼图壁县| 汉沽区| 清远市| 铜陵市| 永济市| 呼伦贝尔市| 新巴尔虎左旗| 承德县| 武定县| 修武县| 将乐县| 恩平市| 阿荣旗| 永定县| 阜宁县| 辽宁省| 恭城| 容城县| 绿春县| 射阳县| 盐津县| 新乡县| 尼玛县| 五峰| 耿马| 屏东市| 绥芬河市| 彭阳县| 邹平县| 青龙| 临猗县| 中阳县| 东城区| 交口县| 静宁县| 桂东县| 腾冲县| 南城县| 台湾省| 清徐县| 广宗县|