本文摘自php中文网,作者小云云,侵删。
本文主要为大家详细介绍了python如何通过实例方法名字调用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。案例:
某项目中,我们的代码使用的2个不同库中的图形类:
Circle,Triangle
这两个类中都有一个获取面积的方法接口,但是接口的名字不一样
需求:
统一这些接口,不关心具体的接口,只要我调用统一的接口,对应的面积就会计算出来
如何解决这个问题?
定义一个统一的接口函数,通过反射:getattr进行接口调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #!/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方法进行调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #!/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通过实例方法名字调用的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python利用openpyxl库遍历sheet的实例
scrapy实现新浪微博爬虫
Python中的for循环语句怎么写
Python sort函数怎么用
Python能做什么工作
Python 怎么用for重复(循环)
Python如何求列表平均值?
初学Python看什么书?
Python程序员待遇如何
Python中的any函数是什么?如何使用any函数?
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python通过实例方法名字调用