Actual case :
In a project , Our code uses three graphics classes from different libraries :Circle,Triangle,Rectangle.
They all have an interface to get the graphic area ( Method ), But the interface name is different . We can implement a unified function to obtain the area , Try each method name , Call the interface of the corresponding class .
Solution :
Method 1( Case solving ): Use built-in functions getattr, Get the method object on the instance by name , And then call .
Method 2( Non case resolution ): Use standard library operator Under the methodcaller Function call .
(1) Case code implementation
class Circle(object): # round
def __init__(self, r):
self.r = r
def area(self):
return self.r ** 2 * 3.14
class Triangle(object): # triangle
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): # rectangular
def __init__(self, w, h):
self.w = w
self.h = h
def get_area(self):
return self.w * self.h
# 3 The area method names of the figures are different from each other
# It is better to implement a function in the user's code , It can unify the area of a graph
def get_area(shape):
# Iterate over those method names , stay shape Object respectively attempts to get method properties
for name in ('area', 'getArea', 'get_area'):
# Call that method if you can get it , Unable to get continue trying
# parameter list : object , name , The default value is None
f = getattr(shape, name, None)
if f:
# Return to the method of obtaining the drawing area
return f()
shape1 = Circle(2)
shape2 = Triangle(3, 4, 5)
shape3 = Rectangle(6, 4)
shapes = [shape1, shape2, shape3]
# Use map Function to obtain shapes The area of each drawing instance in the list
print(list(map(get_area, shapes)))
(2) Method 2 Example demonstration
from operator import methodcaller
s = 'abc123abc456'
# From 4 Start looking for abc character string
print(s.find('abc', 4))
# Use methodcaller Realization s.find
# The first 1 The first parameter is the method name , Then follow the parameter with the method name , Get an object
# This object can make a call , Get the same result as above .
print(methodcaller('find', 'abc', 4)(s))