This article mainly introduces in detail how Python calls methods through instance method names. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
Case:
In a certain project, our code uses graphic classes from two different libraries:
Circle,Triangle
There is a method interface for obtaining area in these two categories, but the names of the interface are different
#:
uniform these interfaces, do not care about specific specifics, do not care about specific specifics, do not care about specific specifics, do not care about specific specifics, do not care about specific specifics. interface, as long as I call the unified interface, the corresponding area will be calculated.
How to solve this problem?
Define a unified interface function and call the interface through reflection: getattr
#!/usr/bin/python3 from math import pi class Circle(object): def __init__(self, radius): self.radius = radius def getArea(self): return round(pow(self.radius, 2) * pi, 2) class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def get_area(self): return self.width * self.height # 定义统一接口 def func_area(obj): # 获取接口的字符串 for get_func in ['get_area', 'getArea']: # 通过反射进行取方法 func = getattr(obj, get_func, None) if func: return func() if __name__ == '__main__': c1 = Circle(5.0) r1 = Rectangle(4.0, 5.0) # 通过map高阶函数,返回一个可迭代对象 erea = map(func_area, [c1, r1]) print(list(erea))
Call through the methodcaller method in the standard library operator
#!/usr/bin/python3 from math import pi from operator import methodcaller class Circle(object): def __init__(self, radius): self.radius = radius def getArea(self): return round(pow(self.radius, 2) * pi, 2) class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def get_area(self): return self.width * self.height if __name__ == '__main__': c1 = Circle(5.0) r1 = Rectangle(4.0, 5.0) # 第一个参数是函数字符串名字,后面是函数要求传入的参数,执行括号中传入对象 erea_c1 = methodcaller('getArea')(c1) erea_r1 = methodcaller('get_area')(r1) print(erea_c1, erea_r1)
The above is the detailed content of python calls by instance method name. For more information, please follow other related articles on the PHP Chinese website!