通过实例方法名字的字符串调用方法
内置函数
getattr
标准库operator
下的methodcaller
函数
class Circle(object):
def __init__(self, r):
self._r = r
def area(self):
return self._r ** 2 * 3.14
class Rectangle(object):
def __init__(self, w, h):
self._w = w
self._h = h
def get_area(self):
return self._w * self._h
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
return (p*(p-a)*(p-b)*(p-c)) ** 0.5
def getarea(shape):
for name in ('area', 'get_area', 'getArea'):
f = getattr(shape, name, None)
if f:
return f()
shape1 = Circle(2)
shape2 = Rectangle(6, 4)
shape3 = Triangle(3, 4, 5)
shapes = [shape1, shape2, shape3]
print(list(map(getarea, shapes)))