from lib1 import Circle
from lib2 import Triangle
from lib3 import Rectangle
from operator import methodcaller
def get_area(shape, method_name = ['area', 'get_area', 'getArea']): #'area', 'get_area', 'getArea'分别是三个图形面积的方法字符串
for name in method_name:
if hasattr(shape, name): #查看是否有这个属性 既对象是否有这个方法
return methodcaller(name)(shape) #(shape)传实例就会调用执行该方法
def get_area2(shape, method_name = ['area', 'get_area', 'getArea']):
for name in method_name:
f = getattr(shape, name, None) #获取对象的方法,如果没有改方法就返回None
if f:
return f()
shape1 = Circle(1)
shape2 = Triangle(3, 4, 5)
shape3 = Rectangle(4, 6)
shape_list = [shape1, shape2, shape3]
# 获得面积列表
area_list = list(map(get_area, shape_list))
print(area_list)
【python】通过方法名字的字符串调用方法
猜你喜欢
转载自blog.csdn.net/qq_38065133/article/details/82356533
今日推荐
周排行