Reflection
For beginners python may be difficult to understand, but reflection is very useful.
Imagine, when another program passed to you to write this code a variable (var= "math"), this variable is a string, the string is a module or a module under a method, you need to import this module or method through a variable, how to import this module or method, if directly execute Import Var is an error, because VAR is a variable in your code, which requires reflection and how to use reflection.
If the value of this variable is a module, you can use Mathmodule=__import__ (VAR), after importing, you can call any method under the math module in your code with mathmodule.***
When you need to get a method under a module, you can use GetAttr, which has specific examples below.
example, how to import the math module by variable import
module= "Math" mathmodule=__import__ (module) print Mathmodule.pow (2,4)
example, how to use the variable import method, the next top of the code
func= "POW" pow=getattr (mathmodule,func) Print pow (2,4)
A specific scenario that uses reflection:
If you have server A and b,a running centralized task distribution, B receives the task given by a
A through the queue to send the task to B, the task is to let B execute the Math.pow method, B to get the task in the queue, it must be used to the reflection
In practical applications, the queue used should be a Message Queuing server, such as a server such as REDIS,ZEROMQ, where the Python queue module is used 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 to put the task you want to perform in the queue.
ServerA ()
Define serverb,b to get tasks in the task queue:
Def ServerB (): task=queue.get () #首先需要导入module if task[' server ']== ' B ': mathmodule=__import__ (Task [' module ']) #其次在module中找到task [' func '] func=getattr (mathmodule,task[' func ')) print func (2,4)
Run the ServerB function to perform the corresponding task.
ServerB ()
Reflection in Python