sys.modules[__name__]

sys.modules[__name__]

https://www.cnblogs.com/robinunix/p/8523601.html

 

A way to get a handle to the current running module in Python:

import sys

module = sys.modules[__name__]

it really only works if you are doing the whole sys.modules litany in the very module you want to get a handle to.

所以,getattr(sys.modules[__name__], func_name)的含義便是找到當前文件下名稱爲func_name的對象(類對象或者函數對象)。

 

有時我們需要將一個文件的信息(類、函數及變量)保存到文件,我們不能直接保存函數對象,而是將其轉化爲fn.__name__,問題來了,當我們想通過讀取文件的形式重新配置這些類、函數時,該如何把這些字符串轉換爲對應的函數對象呢?

# test.py
import sys
def fn():
    print('hello world')
func_name = fn.__name__   ####這個可能是從url中獲取的字符串
fn_obj = getattr(sys.modules[__name__], func_name)
            # 根據函數名(func_name),獲得函數對象
fn_obj()
            # hello world

 

print(sys.modules[__name__])
    # <module '__main__' from '**/test.py'>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章