zoukankan      html  css  js  c++  java
  • Python学习心得(六) 反射机制、装饰器

    1.反射机制

    #/usr/bin/env python
    # -*- coding:utf-8 -*-
    '''
    
    Python反射机制的核心本质:利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动
    
    通俗讲就是通过用户传入url的不同,调用不同的模块函数,好多比较流行的web框架都是通过反射的机制,根据url的不同指向不同的模块
    
    getattr(),hasattr(),setattr(),delattr()对模块的修改都在内存中进行,并不会影响文件中的真实内容    
    
    '''
    
    def run_reflect():
        #以 模块/函数 的形式接收传参
        getstr = raw_input('请输入执行路径:')
    
        #把模块和函数拆分
        modulestr,funstr = getstr.split('/')
    
        try:
            #以字符串的形式导入模块
            module = __import__(modulestr)
        
            #hasattr()内置函数判断模块对象中是否存在属性或方法
            if hasattr(module,funstr):
                #getattr()获取模块对象的属性或方法
                func = getattr(module, funstr) 
                #执行方法
                func()
            else:
                print '模块<' + modulestr + '>中不存在' + funstr + '属性或方法!'
        
            #setattr(对象,字符串,任意值) 设置对象属性值
            setattr(module, 'setAttrValue', 123)    
        
            #判断刚设置的属性是否存在,存在为True,否则False
            print hasattr(module, 'setAttrValue') #打印结果:True
        
            #以字符串的形式删除对象的属性
            delattr(module, 'setAttrValue')
            print hasattr(module, 'setAttrValue') #打印结果:False
        
        except ImportError,e:
            print 'module对象<' + modulestr + '>不存在 && e:' + e
    
    
    if __name__ == '__main__':
        run_reflect()   
    

    - 引用测试的reflect_path1/foo1 模块/函数

    #/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    from pprint import pprint #打印的增强版
    
    class test1():
        commonattr = 'binguo'
        def innerfun(self):
            print 'innerfun'
    
    def foo1():
        dict = {'uid':'20170806','info':'reflect test'}
        pprint(dict)
    

    2.装饰器  

    #/usr/bin/env python
    # -*- coding:utf-8 -*-
    '''
    装饰器:用于对函数或类的代码的封装
    
    由于函数在Python中是作为一级对象的存在,因此它们能够像其他对象一样被传递到另一个函数。
    装饰器就是接受另一个函数作为参数,并用其完成一些操作的函数。
    
    装饰器的应用是通过在装饰器的名称前放置一个@字符,并在被装饰函数声明之上添加一行实现的。
    
    需要注意的一点是:对于某个可调用的函数,可以使用多个装饰器,多个装饰器需要按照自底向上的顺序来应用它们。
    
    
    #内置的装饰器有三个,分别是@staticmethod、@classmethod和@property,作用分别是把类中定义的实例方法变成静态方法、类方法和类属性。
    
    详见下:
    
    '''
    
    #无参情况
    def decorator1(fun):
        def innerdef():
            print 'before decorator' #函数运行前处理常见的前置条件(如确认授权)
            fun() #实际装饰器要封装的无参函数
            print 'after decorator' #函数处理后确保清理(如输出异常处理)
        return innerdef   
    
    #有参情况
    def decorator2(fun): #装饰器可将函数注册到信号系统或注册到web应用程序的url注册表中,总之很有用,以后用的到
        def innerdef(args):
            print 'args:before decorator'
            fun(args) #实际装饰器要封装的有参函数
            print 'args:after decorator'
        return innerdef   
    
        
    @decorator1
    #无参函数应用装饰器
    def foo2():
        print 'function foo2' 
        
    
    @decorator2
    #有参函数应用装饰器
    def foo3(argsvalue):
        print 'function foo3' + '		' + 'argsvalue:' + argsvalue      
        
    foo2()   
    foo3('when input args')    
    

      

      

     

  • 相关阅读:
    echart所有汉字都显示中文,就echarts的toolbox注释显示乱码
    【转】 JSONObject使用方法
    JSON: property "xxx" has no getter method in class "..."
    【转】Oracle数据库中Sequence的用法
    Android实例-获取程序版本号(XE10+小米2)
    Android实例-调用系统APP(XE10+小米2)
    BAT-使用BAT方法清理系统垃圾
    Android实例-全屏显示程序(XE10+小米2)(无图)
    问题-Delphi2007编译时提示内存错误“sxs.dll. No Debug Info.ACCESS 0xXXXXX"
    DelphiXE7中创建WebService(服务端+客户端)
  • 原文地址:https://www.cnblogs.com/binguo2008/p/7296221.html
Copyright © 2011-2022 走看看