1. 程式人生 > >Python——反射機制

Python——反射機制

文章目錄

一、什麼是反射機制

反射是一種基於字串的事件驅動。

它可以通過字串的形式,匯入模組。

通過字串的形式,去模組尋找指定函式,並執行。

利用字串的形式去物件(模組)中操作(查詢/獲取/刪除/新增)成員。

二、反射函式

反射函式是對載入到記憶體中的物件進行操作。

這意味著重新載入模組後,反射操作的物件將復原。

在 Python 中,反射的實現很簡單,主要通過以下 4 個函式:

1、getattr()

在這裡插入圖片描述
我們知道變數實際上的是物件的引用。

getattr() 返回物件名,即返回物件的引用。

其中,

第 1 個引數是目標物件

第 2 個引數是 要獲取的屬性

第 3 個引數default是當需要獲取的屬性不存在時,預設返回的值。如果不設定,當屬性不存在時,則丟擲異常。

2、hasattr()

在這裡插入圖片描述
返回 布林型別。

該函式通過呼叫getattr()實現,即判斷是否拋異常。

3、setattr()

在這裡插入圖片描述

4、delattr()

在這裡插入圖片描述

三、用例

1、動態載入模組,並執行指定的一個函式
imp = input("請輸入模組:")
dd = __import__(imp)
# 等價於import imp
inp_func = input("請輸入要執行的函式:")

f = getattr(dd,inp_func,None)

f() # 執行該函式

這裡說下__import__函式,它用於動態的匯入模組,主要用於反射或者延遲載入模組。

import commons
# 等價於
__import__('commons')

import commons as com
# 等價於
com = __import__('commons')

如果需要載入子模組,需要新增引數 fromlist = True

dd = __import__(imp, fromlist = True)
2、基於反射機制模擬web框架路由
url = input("url: ")

target_module, target_func = url.split('/')
m = __import__('lib.'+target_module, fromlist=True)

inp = url.split("/")[-1]  # 分割url,並取出url最後一個字串
if hasattr(m, target_func):  # 判斷在commons模組中是否存在inp這個字串
    target_func = getattr(m, target_func)  # 獲取inp的引用
    target_func()  # 執行
else:
    print("404")

參考資料

[1] https://www.cnblogs.com/vipchenwei/p/6991209.html#commentform
[2] https://docs.python.org/3/library/index.html