python根據字符串導入模塊

問題:

path = "auth.my_auth.AUTH"  # 根據path實例化AUTH類

解決:

path = "auth.my_auth.AUTH"

import importlib

model_path, class_name = path.rsplit(".", 1)
model = importlib.import_module(model_path)  # 根據"auth.my_auth"導入my_auth模塊
obj = getattr(model, class_name)()  # 反射並實例化
相關文章
相關標籤/搜索