# 如何通过实例方法名字的字符串调用方法
# 要求:
# 某项目中,我们的代码使用了三个不同库中的图形类:Circle,Triangle,Rectangle
# 他们都有一个获取图形面积的接口(方法),但接口名字不同,我们可以实现一个统一的获取面积的函数,使用每种方法名进行城市,调用相应类的接口
class Circle(object):
def __init__(self, r):
self.r = r
def area(self):
return self.r ** 2 * 3.14
class Triangle(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def getArea(self):
a, b, c = self.a, self.b, self.c
p = (a + b + c) / 2
area = (p * (p - a) * (p - b) * (p - c)) ** 0.5
return area
class Rectangle(object):
def __init__(self, w, h):
self.w = w
self.h = h
def get_area(self):
return self.w * self.h
# 第一种方法:使用内置函数getattr,通过名字在实例上获取方法对象,然后掉调用
def getArea(shape):
for name in ('area', 'getArea', 'get_area'):
f = getattr(shape, name, None)
if f:
return f()
shape1 = Circle(2)
shape2 = Triangle(3, 4, 5)
shape3 = Rectangle(6, 4)
shapes = [shape1, shape2, shape3]
print(list(map(getArea, shapes)))
# 第二种方法:使用标准库operator下的methodcaller函数调用
from operator import methodcaller
# 使用示例
s = 'abc123abc456'
# 从第四个位置上开始查找abc的字符串
r = s.find('abc', 4)
print(r)
r = methodcaller('find', 'abc', 4)
print(r(s))