Python功能之反射

有如下文件:

index.py

1
<span style="font-family:'宋体', SimSun;">#!/usr/bin/env python<br data-filtered="filtered"># -*- coding:utf-8 -*-<br data-filtered="filtered">__author__ = 'ryan'<br data-filtered="filtered">"""<br data-filtered="filtered">import home<br data-filtered="filtered">print 'oldboy....'<br data-filtered="filtered">url=raw_input('url:')<br data-filtered="filtered">if url == 'home/dev':<br data-filtered="filtered">    ret = home.dev()<br data-filtered="filtered">    print ret<br data-filtered="filtered">if url =='/home/index':<br data-filtered="filtered">    ret = home.index()<br data-filtered="filtered">    print ret<br data-filtered="filtered">if url =='/home/user':<br data-filtered="filtered">    ret = home.user<br data-filtered="filtered">    print ret<br data-filtered="filtered">if url == '/home/passwd':<br data-filtered="filtered">    ret = home.passwd<br data-filtered="filtered">    print ret<br data-filtered="filtered">else:<br data-filtered="filtered">    print '404'<br data-filtered="filtered">"""<br data-filtered="filtered">#getattr、setattr、delattr、 hasattr<br data-filtered="filtered">#找到home文件,将内容加载到内存,然后getattr、setattr、delattr、 hasattr 对home中断函数进行操作<br data-filtered="filtered">#由于函数在没有执行之前,只是将函数名放入内存<br data-filtered="filtered">import home<br data-filtered="filtered">#print dir(home)<br data-filtered="filtered">#print hasattr(home,'dev')#通过函数hasattr到内存中找到home模块,判断home模块下是否存在dev函数,有返回True,否则返回false<br data-filtered="filtered">#print dir(home)<br data-filtered="filtered">#print getattr(home,'dev')#到内存中的home模块中去获取函数dev(其实时获取dev函数在内存中的地址)<br data-filtered="filtered">#print setattr(home,'alex','gentle man')#通过setattr对内存中的home模块添加一个字符串alex<br data-filtered="filtered">#print dir(home)<br data-filtered="filtered">#delattr(home,'dev')#通过delattr删除内存中home模块中的dev函数<br data-filtered="filtered">#print dir(home)<br data-filtered="filtered">#<br data-filtered="filtered">"""<br data-filtered="filtered">class Foo:<br data-filtered="filtered">    static_name='nba'<br data-filtered="filtered">    def __init__(self):<br data-filtered="filtered">        self.name='alex'<br data-filtered="filtered">    def show(self):<br data-filtered="filtered">        pass<br data-filtered="filtered">    @staticmethod<br data-filtered="filtered">    def static_show(self):<br data-filtered="filtered">        pass<br data-filtered="filtered">    @classmethod<br data-filtered="filtered">    def class_show(cls):<br data-filtered="filtered">        pass<br data-filtered="filtered">#obj=Foo()<br data-filtered="filtered">#print Foo.__dict__.keys() #查看类里面的成员<br data-filtered="filtered">#print hasattr(Foo,'static_show')<br data-filtered="filtered">#print obj.__dict__#查看对象里有哪些成员<br data-filtered="filtered">#print hasattr(obj,'name')<br data-filtered="filtered">#print hasattr(obj,'show')#普通方法是存储在类里,但是这里用hasattr函数在对象obj中查找是否存在show方法,返回了Ture,原因是在对象obj中没有找到之后会通过对象指针到创建对象的类中进一步查找,所以这里返回True<br data-filtered="filtered">"""<br data-filtered="filtered">"""<br data-filtered="filtered">print hasattr(Foo,'__init__')<br data-filtered="filtered">print "##########分隔符①################"<br data-filtered="filtered">print hasattr(Foo,'static_name')<br data-filtered="filtered">print "##########分隔符②################"<br data-filtered="filtered">print hasattr(Foo,'show')<br data-filtered="filtered">print "##########分隔符③################"<br data-filtered="filtered">print hasattr(Foo,'static_show')<br data-filtered="filtered">print "##########分隔符④################"<br data-filtered="filtered">print hasattr(Foo,'class_show')<br data-filtered="filtered">obj=Foo()<br data-filtered="filtered">print obj.__dict__<br data-filtered="filtered">print hasattr(obj,'show')<br data-filtered="filtered">print hasattr(obj,'__init__')<br data-filtered="filtered">print "##########分隔符①################"<br data-filtered="filtered">print hasattr(obj,'static_name')<br data-filtered="filtered">print "##########分隔符②################"<br data-filtered="filtered">print hasattr(obj,'show')<br data-filtered="filtered">print "##########分隔符③################"<br data-filtered="filtered">print hasattr(obj,'static_show')<br data-filtered="filtered">print "##########分隔符④################"<br data-filtered="filtered">print hasattr(obj,'class_show')<br data-filtered="filtered">"""<br data-filtered="filtered">"""<br data-filtered="filtered">import home<br data-filtered="filtered">cls = getattr(home,"Foo")<br data-filtered="filtered">print cls<br data-filtered="filtered">s_name = getattr(cls,'static_name')<br data-filtered="filtered">print s_name<br data-filtered="filtered">c_show = getattr(cls,'show')<br data-filtered="filtered">print c_show<br data-filtered="filtered">s_show=getattr(cls,'static_show')<br data-filtered="filtered">print s_show<br data-filtered="filtered">cla_show = getattr(cls,'class_show')<br data-filtered="filtered">print cla_show<br data-filtered="filtered">"""<br data-filtered="filtered">import home<br data-filtered="filtered">cls = getattr(cls,'Foo')<br data-filtered="filtered">obj=cls()#实例化一个对象obj<br data-filtered="filtered">name = getattr(obj,'name')<br data-filtered="filtered">print name<br data-filtered="filtered"></span>

home.py

1
<span style="font-family:'宋体', SimSun;">#!/usr/bin/env python<br># -*- coding:utf-8 -*-<br>__author__ = 'ryan'<br>def index():<br>    return 'result home.index'<br>def dev():<br>    return 'result home.dev'<br>def user():<br>    return 'result home.user'<br>def passwd():<br>    return 'result home.passwd'<br>"""<br>class Foo:<br>    static_name='nba'<br>    def __init__(self):<br>        self.name='alex'<br>    def show(self):<br>        pass<br>    @staticmethod<br>    def static_show(self):<br>        pass<br>    @classmethod<br>    def class_show(cls):<br>        pass<br>"""<br></span>

反射

fanshe.py

1
<span style="font-family:'宋体', SimSun;">#!/usr/bin/env python<br># -*- coding:utf-8 -*-<br>__author__ = 'ryan'<br>url = raw_input('url:')<br>controller,action =url.split('/')<br>import home<br>#action动作是一个字符串,去某个容器(模块)中去找函数,字符串即为函数名,如果有则获取函数<br>func =getattr(home,action)<br>func = dev dev1():<br>     return 'result home.dev'<br>     ret = func()<br>#func=getattr(home,'index')<br>ret=func()<br>print ret<br></span>


webdemo.py

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
#!/usr/bin/env python
#coding:utf-8
from wsgiref.simple_server import make_server
def RunServer(environ, start_response):
    start_response('200 OK', [('Content-Type''text/html')])
    url = environ['PATH_INFO']
    temp = url.split('/')[1]
    import home
    #去home模块中检查,是否含有指定的函数
    is_exist = hasattr(home, temp)
    #如果存在指定的函数
    if is_exist:
        #获取函数
        func = getattr(home, temp)
        #执行函数并获取返回值
        ret = func()
        #将函数返回值响应响应给请求者,即浏览器
        return ret
    else:
        #如果不存在函数则返回给浏览器'404 not found'
        return '404 not found'
if __name__ == '__main__':
    httpd = make_server('', 8001, RunServer)
    print "Serving HTTP on port 8001..."
    httpd.serve_forever()




      本文转自027ryan  51CTO博客,原文链接:http://blog.51cto.com/ucode/1763328,如需转载请自行联系原作者



上一篇:ES6 对象的扩展(下)


下一篇:Java知识积累——单元测试和JUnit(一)