python中的反射

反射

对于初学python可能较难理解,但反射是很实用。


试想一下,当别的程序传入给你写的这段代码一个变量(var=“math”),这个变量是一个字符串,这个字符串是一个模块或者一个模块下的某个方法,你须要通过变量来导入此模块或者方法,怎样导入此模块或方法呢,假设直接运行 import var是会出错的。由于var在你的这段代码中是一个变量, 这时就须要反射。 怎样使用反射呢。

假设这个变量值是一个模块。能够使用MathModule=__import__(var), 导入后,你能够在你的代码中用MathModule.***来调用math模块下的随意方法

当须要获得一个模块下的某个方法时。能够使用getattr,以下有详细的样例。


样例,怎样导入通过变量导入math模块

module="math"
MathModule=__import__(module)
print MathModule.pow(2,4)


样例。怎样通过变量导入方法,接上边的代码

func="pow"
pow=getattr(MathModule,func)
print pow(2,4)

一个使用反射的详细场景:

假如有serverA和B,A执行的是集中化任务分发,B接收A给出的任务

A通过queue把任务发送给B,任务内容是让B运行math.pow方法。B去queue中获取任务。此时就必需要使用到反射

在实际应用中,使用的queue应该是消息队列server。比如Redis,zeromq等server。这里使用python的Queue模块来模拟



定义一个队列:

import Queue
queue=Queue.Queue()

定义ServerA

def ServerA():
    Dict={'server':'B','module':'math','func':'pow'}
    queue.put(Dict)
执行ServerA函数。将须要执行的任务放入队列中.

ServerA()

定义ServerB,B去任务队列中获取任务:

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)


执行ServerB函数, 执行对应的任务.

ServerB()    






posted on 2016-04-20 14:11  gcczhongduan  阅读(190)  评论(0编辑  收藏  举报