代码使用了三个不同库中的图形类:Circle,Triangle,Rectangle
都有一个获取图形面积的接口,但接口名字不同,需实现一个统一的获取面积的函数,使用每种方法名进行尝试,调用相应类的接口
# lib1.py
calss Circle(object):
def __init__(self, r):
self.r = r
def area(self):
return self.r ** 2 * 3.14
# lib2.py
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
# lib3.py
class Rectangle(object):
def __init__(self, w, h):
self.w = w
self.h = h
def get_area(self):
return self.w * self.h
#
from lib1 import Circle
from lib2 import Triangle
from lib3 import Rectangle
def getArea(shape):
pass
shape1 = Circle(2)
shape2 = Triangle(3,4,5)
shape3 = Rectangle(6, 4)
shapes = [shape1,shape2,shape3]
print map(getArea, shapes)
#
方法一:使用内置函数getattr,通过名字在实例上获取方法对象,调用
from lib1 import Circle
from lib2 import Triangle
from lib3 import Rectangle
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 map(getArea, shapes)
方法二:使用标准库operator下的methodcaller函数调用
from operator import methodcaller
s = 'abc123abc456'
s.find('abc',4) # 6 ;从第4个位置开始查找abc
methodcaller('find','abc',4)(s) # 6
#
from lib1 import Circle
from lib2 import Triangle
from lib3 import Rectangle
from operator import methodcaller
def getArea(shape):
for name in ('area','getArea','get_area'):
res = methodcaller(name)(shape)
return res
shape1 = Circle(2)
shape2 = Triangle(3,4,5)
shape3 = Rectangle(6, 4)
shapes = [shape1,shape2,shape3]
print map(getArea, shapes)
6.5【类与对象】通过实例方法名字的字符串调用方法
最新推荐文章于 2024-10-02 10:53:34 发布