This article is mainly for you in detail how Python through the instance method name call method, has a certain reference value, interested in small partners can refer to, hope to help everyone.
Case:
In a project, our code uses the graphics classes in 2 different libraries:
Circle,triangle
Each of the two classes has a method interface that gets the area, but the interface has a different name
Requirements:
Unify these interfaces, do not care about the specific interface, as long as I call the Unified interface, the corresponding area will be calculated
How to solve this problem?
Defines a unified interface function that is called by 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 # defines the Unified interface Def func_area (obj): # Gets the string for the interface for get_func in [' Get_area ', ' Getarea ']: # Take the method via reflection func = GetAttr (obj, Get_func, None) if func: return func () if __name__ = = ' __main_ _ ': C1 = Circle (5.0) r1 = Rectangle (4.0, 5.0) # Returns an iterative object Erea = Map (Func_area, [C1, R1]) via the map higher order function: C23/>print (List (Erea))
Call by Methodcaller method in standard library operator
#!/usr/bin/python3 from math import pifrom 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) # The first argument is the function string name, followed by the function required to pass in the arguments, execute parentheses in the incoming object EREA_C1 = Methodcaller (' Getarea ') (c1) Erea_r1 = Methodcaller (' Get_ar EA ') (R1) print (EREA_C1, erea_r1)