python(27)反射機制

1. 什麼是反射?

它的核心本質其實就是基於字元串的事件驅動,通過字元串的形式去操作對象的屬性或者方法
 

2. 反射的優點

一個概念被提出來,就是要明白它的優點有哪些,這樣我們才能知道為什麼要使用反射。

2.1 場景構造

開發1個網站,由兩個文件組成,一個是具體執行操作的文件commons.py,一個是入口文件visit.py
需求:需要在入口文件中設置讓用戶輸入url, 根據用戶輸入的url去執行相應的操作

# commons.py
def login():
    print("這是一個登陸頁面!")


def logout():
    print("這是一個退出頁面!")


def home():
    print("這是網站主頁面!")
# visit.py
import commons


def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    if inp == 'login':
        commons.login()
    elif inp == 'logout':
        commons.logout()
    elif inp == 'index':
        commons.home()
    else:
        print('404')


if __name__ == '__main__':
    run()

運行run方法後,結果如下:

請輸入您想訪問頁面的url:  login
這是一個登陸頁面!

提問:上面使用if判斷,根據每一個url請求去執行指定的函數,若commons.py中有100個操作,再使用if判斷就不合適了
回答:使用python反射機制,commons.py文件內容不變,修改visit.py文件,內容如下

import commons


def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    if hasattr(commons, inp):
        getattr(commons, inp)()
    else:
        print("404")


if __name__ == '__main__':
    run()

使用這幾行程式碼,可以應對​​commons.py​​文件中任意多個頁面函數的調用!
 

反射中的內置函數

 

getattr

def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value
    
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass

​​getattr()​​​函數的第一個參數需要是個對象,上面的例子中,我導入了自定義的commons模組,commons就是個對象;第二個參數是指定前面對象中的一個方法名稱。
​​getattr(x, 'y')​​​ 等價於執行了 ​x.y​​​。假如第二個參數輸入了前面對象中不存在的方法,該函數會拋出異常並退出。所以這個時候,為了程式的健壯性,我們需要先判斷一下該對象中有沒有這個方法,於是用到了​​hasattr()​​函數
 

hasattr

def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.
    
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass

​​hasattr()​​​函數返回對象是否擁有指定名稱的屬性,簡單的說就是檢查在第一個參數的對象中,能否找到與第二參數名相同的方法。源碼的解釋還說,該函數的實現其實就是調用了​​getattr()​​​函數,只不過它捕獲了異常而已。所以通過這個函數,我們可以先去判斷對象中有沒有這個方法,有則使用​​getattr()​​來獲取該方法。
 

setattr

def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass

​​setattr()​​​函數用來給指定對象中的方法重新賦值(將新的函數體/方法體賦值給指定的對象名)僅在本次程式運行的記憶體中生效。​​setattr(x, 'y', v)​​​ 等價於 ​​x.y = v​
 

delattr

def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass

刪除指定對象中的指定方法,特別提示:只是在本次運行程式的記憶體中將該方法刪除,並沒有影響到文件的內容
 

__import__模組反射

接著上面網站的例子,現在一個後台文件已經不能滿足我的需求,這個時候需要根據職能劃分後台文件,現在我又新增了一個​​user.py這個用戶類的文件,也需要導入到首頁以備調用。
 

但是,上面網站的例子,我已經寫死了只能指定commons模組的方法任意調用,現在新增了user模組,那此時我又要使用if判斷?
答:不用,使用Python自帶的函數__import__
 

由於模組的導入也需要使用Python反射的特性,所以模組名也要加入到url中,所以現在url請求變成了類似於​​commons/visit​​的形式

# user.py
def add_user():
    print('添加用戶')


def del_user():
    print('刪除用戶')
# commons.py
def login():
    print("這是一個登陸頁面!")


def logout():
    print("這是一個退出頁面!")


def home():
    print("這是網站主頁面!")
# visit.py
def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    # modules代表導入的模組,func代表導入模組裡面的方法
    modules, func = inp.split('/')
    obj_module = __import__(modules)
    if hasattr(obj_module, func):
        getattr(obj_module, func)()
    else:
        print("404")


if __name__ == '__main__':
    run()

最後執行run函數,結果如下:

請輸入您想訪問頁面的url:  user/add_user
添加用戶

請輸入您想訪問頁面的url:  user/del_user
刪除用戶

現在我們就能體會到__import__的作用了,就是把字元串當做模組去導入。
 

但是如果我的網站結構變成下面的

|- visit.py
|- commons.py
|- user.py
|- lib
    |- __init__.py
    |- connectdb.py

現在我想在​​visit​​​頁面中調用​​lib​​​包下​​connectdb​​模組中的方法,還是用之前的方式調用可以嗎?

# connectdb.py
def conn():
    print("已連接mysql")
# visit.py
def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    # modules代表導入的模組,func代表導入模組裡面的方法
    modules, func = inp.split('/')
    obj_module = __import__('lib.' + modules)
    if hasattr(obj_module, func):
        getattr(obj_module, func)()
    else:
        print("404")


if __name__ == '__main__':
    run()

運行run命令,結果如下:

請輸入您想訪問頁面的url:  connectdb/conn
404

結果顯示找不到,為了測試調用lib下的模組,我拋棄了對所有同級目錄模組的支援,所以我們需要查看__import__源碼

def __import__(name, globals=None, locals=None, fromlist=(), level=0): # real signature unknown; restored from __doc__
    """
    __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module
    
    Import a module. Because this function is meant for use by the Python
    interpreter and not for general use, it is better to use
    importlib.import_module() to programmatically import a module.
    
    The globals argument is only used to determine the context;
    they are not modified.  The locals argument is unused.  The fromlist
    should be a list of names to emulate ``from name import ...'', or an
    empty list to emulate ``import name''.
    When importing a module from a package, note that __import__('A.B', ...)
    returns package A when fromlist is empty, but its submodule B when
    fromlist is not empty.  The level argument is used to determine whether to
    perform absolute or relative imports: 0 is absolute, while a positive number
    is the number of parent directories to search relative to the current module.
    """
    pass

​​__import__​​​函數中有一個​​fromlist​​參數,源碼解釋說,如果在一個包中導入一個模組,這個參數如果為空,則return這個包對象,如果這個參數不為空,則返回包下面指定的模組對象,所以我們上面是返回了包對象,所以會返回404的結果,現在修改如下:

# visit.py
def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    # modules代表導入的模組,func代表導入模組裡面的方法
    modules, func = inp.split('/')
    # 只新增了fromlist=True
    obj_module = __import__('lib.' + modules, fromlist=True)
    if hasattr(obj_module, func):
        getattr(obj_module, func)()
    else:
        print("404")


if __name__ == '__main__':
    run()

運行run方法,結果如下:

請輸入您想訪問頁面的url:  connectdb/conn
已連接mysql

成功了,但是我寫死了lib前綴,相當於拋棄了commonsuser兩個導入的功能,所以以上程式碼並不完善,需求複雜後,還是需要對請求的url做一下判斷

def getf(module, func):
    """
    抽出公共部分
    """
    if hasattr(module, func):
        func = getattr(module, func)
        func()
    else:
        print('404')


def run():
    inp = input("請輸入您想訪問頁面的url:  ").strip()
    if len(inp.split('/')) == 2:
        # modules代表導入的模組,func代表導入模組裡面的方法
        modules, func = inp.split('/')
        obj_module = __import__(modules)
        getf(obj_module, func)
    elif len(inp.split("/")) == 3:
        p, module, func = inp.split('/')
        obj_module = __import__(p + '.' + module, fromlist=True)
        getf(obj_module, func)


if __name__ == '__main__':
    run()

運行run函數,結果如下:

請輸入您想訪問頁面的url:  lib/connectdb/conn
已連接mysql

請輸入您想訪問頁面的url:  user/add_user
添加用戶

當然你也可以繼續優化程式碼,現在只判斷了有1個斜杠和2個斜杠的,如果目錄層級更多呢,這個暫時不考慮,本次是為了了解python的反射機制