1. 程式人生 > >Python學習心得(六) 反射機制、裝飾器

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' + '\t\t' + 'argsvalue:' + argsvalue      
    
foo2()   
foo3('when input args')    

部落格園同步地址: