温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python通过实例方法名字调用方法的案例

发布时间:2021-02-18 12:58:42 来源:亿速云 阅读:152 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关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 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)
  
 # 第一个参数是函数字符串名字,后面是函数要求传入的参数,执行括号中传入对象
 erea_c1 = methodcaller('getArea')(c1)
 erea_r1 = methodcaller('get_area')(r1)
 print(erea_c1, erea_r1)

感谢各位的阅读!关于“python通过实例方法名字调用方法的案例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI