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/python3from Math Import Piclass 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# Definition Unified Interface def func_area (obj): # Gets the string for the interface for get_func in [' Get_area ', ' Getarea ']: # Method of fetching by reflection C12/>func = GetAttr (obj, Get_func, None) if func: return func () if __name__ = = ' __main__ ': c1 = CIRCL E (5.0) r1 = Rectangle (4.0, 5.0) # Returns an iterative object Erea = Map (Func_area, [C1, R1]) through the map higher order function, print (list ( Erea))
Call by Methodcaller method in standard library operator
#!/usr/bin/python3from Math Import pifrom operator import Methodcallerclass 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.heightif __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_ Area ') (R1) print (EREA_C1, EREA_R1)
Python_ How do I call methods by instance method name?