6.5【类与对象】通过实例方法名字的字符串调用方法

代码使用了三个不同库中的图形类: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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值