Reflection in python and python reflection
Reflection
It may be difficult to understand python for beginners, but reflection is very useful.
Think about it. When another program sends a variable (var = "math") to the code you write, this variable is a string, this string is a method in a module or module. You need to use variables to import this module or method. How can you import this module or method, if you directly execute import var, an error occurs. Because var is a variable in your code, reflection is required. How can we use reflection.
If the value of this variable is a module, you can use MathModule =__ import _ (var). After importing the variable, you can use MathModule in your code. *** call any method in the math module
To obtain a method under a module, you can use getattr. The following is an example.
Example: How to import a math module through a variable
module="math"MathModule=__import__(module)print MathModule.pow(2,4)
Example: How to Use the variable import method to connect the edge code
func="pow"pow=getattr(MathModule,func)print pow(2,4)
A specific scenario for reflection:
Assume that servers A and B run centralized task distribution, and B receives the task given by.
A sends the task to B through queue. The content of the task is to let B execute the math. pow method, and B gets the task from queue. At this time, reflection must be used.
In practical applications, the used queue should be a Message Queue Server, such as Redis and zeromq. Here we use the python queue module to simulate
Define a queue:
import Queuequeue=Queue.Queue()
Define ServerA
def ServerA(): Dict={'server':'B','module':'math','func':'pow'} queue.put(Dict)
Run the ServerA function and put the task to be executed into the queue.
ServerA()
Define ServerB and B to get the task from the task queue:
Def ServerB (): task = queue. get () # first import module if task ['server'] = 'B': MathModule =__ import _ (task ['module']) # Find task ['function'] func = getattr (MathModule, task ['function']) print func (2, 4) in module)
Run the ServerB function to execute the corresponding task.
ServerB()