python 反射

反射的简单含义:

     通过方法名得到未知的方法(方法名不确定),实现调用。

     即:当我们需要执行对象的某个方法,或是需要对对象的某个字段赋值时,而方法名或是字段名在编码代码时并不能确定,需要通过参数传递字符串的形式输入。下面是一个小例子:

     

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# -*- coding:utf-8 -*-
__author__ = 'webber'
import time
 
class myClass(object):
    name = 'test'
 
    def cpu(self):
        print 'cpu func start!!!'
 
    def mem(self):
        print 'mem func start!!!'
 
    def disk(self):
        print 'disk func start!!!'
 
def newfunc():
    print ''
    print "new func \033[31;1m%s\033[0m has start!!!!" % user_input
 
m = myClass()
user_input = "test"   #raw_input("please input command:")
if hasattr(m, user_input):   #判断类内是否有该方法
    func = getattr(m, user_input)  #获取类内的该方法,并赋给func
    func()                         #执行该方法
else:
    print "----> \033[31;1m%s\033[0m is not exist!!!" % user_input
    print 'please wait......'
    for i in range(3):
        time.sleep(1)
        print '..',
    setattr(m, user_input, newfunc)   #根据用户的错误输入,使用户自定义一个方法
    func = getattr(m, user_input)
    func()
 
    print 'run test' ,m.test()    #这里,test已经成为m实例化下的newfunc的新方法名,可供调用

 


输出结果如下:
----> test is not exist!!!
please wait......
.. .. ..
new func test has start!!!!
run test
new func test has start!!!!
None


下面在贴个实例(别人的):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#-*-coding:utf-8-*-
'''
copy from http://www.linuxidc.com/Linux/2015-03/115091.htm
python反射的一个应用场景:
假设有服务器A和B,A运行的是集中化任务分发,B接收A给出的任务
A通过queue把任务发送给B,任务内容是让B执行math.pow方法,B去queue中获取任务,此时就必须要使用到反射
在实际应用中,使用的queue应该是消息队列服务器,例如Redis,zeromq等服务器,这里使用python的Queue模块来模拟
 
'''
import Queue
queue=Queue.Queue()
 
#定义ServerA
def ServerA():
    Dict = {'server':'B','module':'math','func':'pow'}
    queue.put(Dict)
 
#运行ServerA函数,将需要执行的任务放入队列中.
ServerA()
 
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,5)      #这里就相当于执行了pow(2,5)函数
 
#运行ServerB函数, 执行相应的任务.
ServerB()

 


这里,成功的在Server B上执行了pow方法。输出结果:32.0

 

posted @   webber_liu  阅读(154)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示