某项目中,代码使用了三个不同库中的图形类:Circle
,Triangle
,Rectangle
,它们都有一个获取图形面积的接口(方法),但方法名字不同。
要求:实现一个统一的获取面积的函数,使用各种方法名进行尝试,调用相应类的接口。
解决方案:
-
使用内置函数
getattr()
,通过名字获取方法对象,然后调用。 -
使用标准库operator下的
methodcaller()
函数调用。
- 对于内置函数
getattr()
:
getattr(object, name[, default])
返回对象命名属性的值。name必须是字符串。如果该字符串是对象的属性之一,则返回该属性的值。例如getattr(x, 'foobar')
等同于x.foobar
。如果指定的属性不存在,且提供了default值,则返回它,否则触发AttributeError。
>>> s = 'abc123'
>>> s.find('123')
3
>>> getattr(s, 'find', None)('123') #等同于s.find('123')
3
- 对于
methodcaller()
函数:
operator.methodcaller(name[, args...])
methodcaller()
函数会返回一个可调用对象,该对象在其操作数上调用方法名。如果提供了额外的参数或关键字参数,它们也将被提供给方法。
>>> from operator import methodcaller
>>> s = 'abc123abc456'
>>> s.find('abc', 3)
6
>>> methodcaller('find', 'abc', 3)(s) #等价于s.find('abc', 3)
6
lib1.py
class Triangle:
def __init__(self, a, b, c):
self.a, self.b, self.c = a,b,c
def get_area(self):
a,b,c = self.a, self.b, self.c
p = (a+b+c) / 2
return (p * (p-a) * (p-b) * (p-c)) ** 0.5
lib2.py
class Rectangle:
def __init__(self, a, b):
self.a, self.b = a,b
def getarea(self):
return self.a * self.b
lib3.py
import math
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return round(self.r ** 2 * math.pi, 1)
- 方案1示例:
from lib1 import Triangle
from lib2 import Rectangle
from lib3 import Circle
def get_area(shape, method_name = ['get_area', 'getarea', 'area']):
for name in method_name:
f = getattr(shape, name, None)
if f: return f()
shape1 = Triangle(3, 4, 5)
shape2 = Rectangle(4, 6)
shape3 = Circle(2)
shape_list = [shape1, shape2, shape3]
area_list = list(map(get_area, shape_list))
print(area_list)
[6.0, 24, 12.6] #结果
- 方案2示例:
from lib1 import Triangle
from lib2 import Rectangle
from lib3 import Circle
from operator import methodcaller
def get_area(shape, method_name = ['get_area', 'getarea', 'area']):
for name in method_name:
if hasattr(shape, name):
return methodcaller(name)(shape)
shape1 = Triangle(3, 4, 5)
shape2 = Rectangle(4, 6)
shape3 = Circle(2)
shape_list = [shape1, shape2, shape3]
area_list = list(map(get_area, shape_list))
print(area_list)
[6.0, 24, 12.6] #结果