python如何通過執行個體方法名字調用方法,python執行個體

來源:互聯網
上載者:User

python如何通過執行個體方法名字調用方法,python執行個體

本文執行個體為大家分享了python通過執行個體方法名字調用方法的具體代碼,供大家參考,具體內容如下

案例:

       某項目中,我們的代碼使用的2個不同庫中的圖形類:

              Circle,Triangle

       這兩個類中都有一個擷取面積的方法介面,但是介面的名字不一樣

       需求:

              統一這些介面,不關心具體的介面,只要我調用統一的介面,對應的面積就會計算出來

如何解決這個問題?

定義一個統一的介面函數,通過反射: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  # 定義統一介面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 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)     # 第一個參數是函數字串名字,後面是函數要求傳入的參數,執行括弧中傳入對象  erea_c1 = methodcaller('getArea')(c1)  erea_r1 = methodcaller('get_area')(r1)  print(erea_c1, erea_r1)

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.